// Quantum Compatibility Service
// Universal compatibility layer for legacy protocols

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { logger } from '@/infrastructure/monitoring/logger';
import { ALL_LEGACY_PROTOCOLS, type LegacyProtocol } from './legacy-protocol-types';

export interface CompatibilityCheckRequest {
  legacyProtocol: LegacyProtocol;
  transactionData: any;
}

export interface CompatibilityCheckResult {
  compatible: boolean;
  compatibilityScore: number;
  issues: string[];
  recommendations: string[];
}

export class QuantumCompatibilityService {
  /**
   * Check compatibility of legacy protocol with quantum systems
   */
  async checkCompatibility(
    request: CompatibilityCheckRequest
  ): Promise<CompatibilityCheckResult> {
    logger.info('QPS: Checking compatibility', {
      legacyProtocol: request.legacyProtocol,
    });

    const issues: string[] = [];
    const recommendations: string[] = [];
    let compatibilityScore = 100;

    // Check protocol-specific compatibility
    switch (request.legacyProtocol) {
      case 'SWIFT':
        compatibilityScore = await this.checkSwiftCompatibility(
          request.transactionData,
          issues,
          recommendations
        );
        break;

      case 'ISO20022':
        compatibilityScore = await this.checkIso20022Compatibility(
          request.transactionData,
          issues,
          recommendations
        );
        break;

      case 'ACH':
        compatibilityScore = await this.checkAchCompatibility(
          request.transactionData,
          issues,
          recommendations
        );
        break;

      case 'SEPA':
        compatibilityScore = await this.checkSepaCompatibility(
          request.transactionData,
          issues,
          recommendations
        );
        break;

      case 'PRIVATE_BANK':
        compatibilityScore = await this.checkPrivateBankCompatibility(
          request.transactionData,
          issues,
          recommendations
        );
        break;

      case 'KTT_EVIDENCE':
      case 'TT_ROUTE':
      case 'DTC_SETTLEMENT':
      case 'DTCC_NSCC':
      case 'DTCC_FICC':
      case 'SWIFT_GPI':
      case 'MOJALOOP':
      case 'RTGS':
      case 'CARD_NETWORK':
        compatibilityScore = this.checkSolaceNetRailScaffoldCompatibility(
          request.legacyProtocol,
          issues,
          recommendations
        );
        break;

      default:
        issues.push(`Unknown protocol: ${request.legacyProtocol}`);
        compatibilityScore = 0;
    }

    const compatible = compatibilityScore >= 70;

    return {
      compatible,
      compatibilityScore,
      issues,
      recommendations,
    };
  }

  /**
   * SolaceNet-aligned rail scaffolds: neutral score until real field contracts exist.
   */
  private checkSolaceNetRailScaffoldCompatibility(
    protocol: LegacyProtocol,
    issues: string[],
    recommendations: string[]
  ): number {
    issues.push(`Scaffold protocol mapping for ${protocol}; validate against live rail contract before production.`);
    recommendations.push(
      'See dbis_core/docs/solacenet/PROTOCOL_GAPS_CHECKLIST.md and gateway-adapter-registry for adapter status.'
    );
    return 72;
  }

  /**
   * Check SWIFT compatibility
   */
  private async checkSwiftCompatibility(
    transactionData: any,
    issues: string[],
    recommendations: string[]
  ): Promise<number> {
    let score = 90; // SWIFT is highly compatible

    // Check required fields
    if (!transactionData.sender) {
      issues.push('Missing sender field');
      score -= 10;
    }
    if (!transactionData.receiver) {
      issues.push('Missing receiver field');
      score -= 10;
    }
    if (!transactionData.amount) {
      issues.push('Missing amount field');
      score -= 10;
    }

    if (score < 90) {
      recommendations.push('Ensure all required SWIFT fields are present');
    }

    return Math.max(0, score);
  }

  /**
   * Check ISO20022 compatibility
   */
  private async checkIso20022Compatibility(
    transactionData: any,
    issues: string[],
    recommendations: string[]
  ): Promise<number> {
    let score = 95; // ISO20022 is highly compatible (standard format)

    // ISO20022 is already quantum-compatible
    if (!transactionData.debtor && !transactionData.creditor) {
      issues.push('Missing debtor/creditor fields');
      score -= 5;
    }

    return Math.max(0, score);
  }

  /**
   * Check ACH compatibility
   */
  private async checkAchCompatibility(
    transactionData: any,
    issues: string[],
    recommendations: string[]
  ): Promise<number> {
    let score = 85; // ACH is compatible but may need conversion

    if (!transactionData.originator) {
      issues.push('Missing originator field');
      score -= 10;
    }
    if (!transactionData.receiver) {
      issues.push('Missing receiver field');
      score -= 10;
    }

    recommendations.push('ACH transactions may require domestic currency conversion');

    return Math.max(0, score);
  }

  /**
   * Check SEPA compatibility
   */
  private async checkSepaCompatibility(
    transactionData: any,
    issues: string[],
    recommendations: string[]
  ): Promise<number> {
    let score = 90; // SEPA is compatible (EU standard)

    if (!transactionData.debtor) {
      issues.push('Missing debtor field');
      score -= 10;
    }
    if (!transactionData.creditor) {
      issues.push('Missing creditor field');
      score -= 10;
    }

    if (transactionData.currencyCode !== 'EUR') {
      recommendations.push('SEPA transactions should use EUR currency');
      score -= 5;
    }

    return Math.max(0, score);
  }

  /**
   * Check private bank compatibility
   */
  private async checkPrivateBankCompatibility(
    transactionData: any,
    issues: string[],
    recommendations: string[]
  ): Promise<number> {
    let score = 70; // Private bank protocols vary

    if (!transactionData.from) {
      issues.push('Missing from field');
      score -= 15;
    }
    if (!transactionData.to) {
      issues.push('Missing to field');
      score -= 15;
    }

    recommendations.push('Private bank protocols may require custom mapping');
    recommendations.push('Verify transaction format matches expected schema');

    return Math.max(0, score);
  }

  /**
   * Register protocol mapping
   */
  async registerProtocolMapping(
    legacyProtocol: string,
    mappingConfig: any
  ): Promise<string> {
    const mappingId = `QPS-MAP-${uuidv4()}`;

    await prisma.legacy_protocol_mappings.create({
      data: {
        mappingId,
        legacyProtocol,
        mappingConfig: mappingConfig as any,
        status: 'active',
      },
    });

    logger.info('QPS: Protocol mapping registered', {
      mappingId,
      legacyProtocol,
    });

    return mappingId;
  }

  /**
   * Get protocol mapping
   */
  async getProtocolMapping(legacyProtocol: string) {
    return await prisma.legacy_protocol_mappings.findFirst({
      where: { legacyProtocol, status: 'active' },
    });
  }

  /**
   * List all supported protocols
   */
  async listSupportedProtocols(): Promise<string[]> {
    return [...ALL_LEGACY_PROTOCOLS];
  }
}

export const quantumCompatibilityService = new QuantumCompatibilityService();

