// Capacity Tier Assessor Service
// Determines appropriate capacity tier

export interface CapacityAssessmentResult {
  requestedTier: number;
  recommendedTier: number;
  reasoning: string;
  riskScore: number;
  usageProfile: {
    estimatedVolume: string;
    transactionTypes: string[];
    peakLoad: string;
  };
}

export class CapacityTierAssessor {
  /**
   * Assess capacity tier
   */
  async assess(
    institutionalType: string,
    estimatedVolume?: string,
    preliminaryInfo?: any
  ): Promise<CapacityAssessmentResult> {
    // Default tier based on institutional type
    let recommendedTier = 3; // Default to Commercial Bank tier

    switch (institutionalType) {
      case 'CentralBank':
        recommendedTier = 1;
        break;
      case 'SettlementBank':
        recommendedTier = 2;
        break;
      case 'CommercialBank':
        recommendedTier = 3;
        break;
      case 'DFI':
        recommendedTier = 4;
        break;
      case 'SpecialEntity':
        recommendedTier = 5;
        break;
    }

    // Adjust based on estimated volume if provided
    if (estimatedVolume) {
      const volume = this.parseVolume(estimatedVolume);
      if (volume > 10000000) {
        // > 10M transactions/month
        if (recommendedTier > 1) recommendedTier = Math.max(1, recommendedTier - 1);
      } else if (volume < 100000) {
        // < 100K transactions/month
        if (recommendedTier < 5) recommendedTier = Math.min(5, recommendedTier + 1);
      }
    }

    // Adjust based on preliminary info
    if (preliminaryInfo?.transactionTypes) {
      const hasHighValueTransactions = preliminaryInfo.transactionTypes.some((type: string) =>
        ['RTGS', 'FX', 'Settlement'].includes(type)
      );
      if (hasHighValueTransactions && recommendedTier > 2) {
        recommendedTier = Math.max(2, recommendedTier - 1);
      }
    }

    const requestedTier = preliminaryInfo?.requestedTier || recommendedTier;
    const riskScore = requestedTier !== recommendedTier ? 40 : 20;

    return {
      requestedTier,
      recommendedTier,
      reasoning: this.generateReasoning(institutionalType, recommendedTier, estimatedVolume),
      riskScore,
      usageProfile: {
        estimatedVolume: estimatedVolume || 'Not specified',
        transactionTypes: preliminaryInfo?.transactionTypes || [],
        peakLoad: preliminaryInfo?.peakLoad || 'Not specified',
      },
    };
  }

  /**
   * Parse volume string to number
   */
  private parseVolume(volumeStr: string): number {
    const match = volumeStr.match(/(\d+(?:\.\d+)?)\s*([KMkm]?)/);
    if (!match) return 0;

    const number = parseFloat(match[1]);
    const unit = match[2].toUpperCase();

    switch (unit) {
      case 'K':
        return number * 1000;
      case 'M':
        return number * 1000000;
      default:
        return number;
    }
  }

  /**
   * Generate reasoning for tier recommendation
   */
  private generateReasoning(
    institutionalType: string,
    tier: number,
    estimatedVolume?: string
  ): string {
    const tierNames: Record<number, string> = {
      1: 'Central Banks',
      2: 'Settlement Banks',
      3: 'Commercial Banks',
      4: 'Development Finance Institutions',
      5: 'Special Entities',
    };

    let reasoning = `Recommended Tier ${tier} (${tierNames[tier]}) based on institutional type: ${institutionalType}`;

    if (estimatedVolume) {
      reasoning += ` and estimated volume: ${estimatedVolume}`;
    }

    return reasoning;
  }
}

export const capacityTierAssessor = new CapacityTierAssessor();
