// GRU Legal Framework Service
// Implements SMIA, DRGC, IMCP compliance and ISO 4217/6166/ICC UCP 600/FATF checks

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { logger } from '@/infrastructure/monitoring/logger';


export type LegalFrameworkType = 'SMIA' | 'DRGC' | 'IMCP';
export type ComplianceType =
  | 'ISO_4217'
  | 'ISO_6166'
  | 'ICC_UCP_600'
  | 'FATF_AML_CTF'
  | 'SMIA'
  | 'DRGC'
  | 'IMCP';
export type ComplianceStatus = 'pending' | 'compliant' | 'non_compliant' | 'exempt';

export interface LegalFrameworkComplianceRequest {
  issuanceId?: string;
  complianceTypes: ComplianceType[];
  verifyDetails?: Record<string, any>;
}

export interface ComplianceVerificationResult {
  recordId: string;
  complianceType: string;
  complianceStatus: string;
  verified: boolean;
  details?: any;
}

export class GruLegalFrameworkService {
  /**
   * Initialize legal frameworks if they don't exist
   */
  async initializeFrameworks(): Promise<void> {
    const frameworks = [
      {
        frameworkType: 'SMIA',
        frameworkName: 'Sovereign Monetary Instruments Act',
        description:
          'Legal framework governing sovereign monetary instruments and their issuance authority',
        complianceRequired: true,
      },
      {
        frameworkType: 'DRGC',
        frameworkName: 'DBIS Reserve Governance Charter',
        description:
          'DBIS charter establishing reserve governance and supervisory authority',
        complianceRequired: true,
      },
      {
        frameworkType: 'IMCP',
        frameworkName: 'International Monetary Compliance Protocols',
        description:
          'International protocols for monetary compliance and cross-border coordination',
        complianceRequired: true,
      },
    ];

    for (const frameworkData of frameworks) {
      const existing = await prisma.gruLegalFramework.findUnique({
        where: { frameworkType: frameworkData.frameworkType },
      });

      if (!existing) {
        await prisma.gruLegalFramework.create({
          data: {
            frameworkId: `GRU-FW-${uuidv4()}`,
            ...frameworkData,
            status: 'active',
          },
        });

        logger.info(`GRU Legal Framework: Initialized ${frameworkData.frameworkType}`);
      }
    }
  }

  /**
   * Verify legal framework compliance
   */
  async verifyCompliance(
    request: LegalFrameworkComplianceRequest
  ): Promise<ComplianceVerificationResult[]> {
    logger.info('GRU Legal Framework: Verifying compliance', { request });

    const results: ComplianceVerificationResult[] = [];

    for (const complianceType of request.complianceTypes) {
      const verification = await this.verifyComplianceType(
        complianceType,
        request.issuanceId,
        request.verifyDetails
      );

      // Create compliance record
      const framework = await this.getFrameworkForComplianceType(complianceType);
      if (framework) {
        const record = await prisma.gruComplianceRecord.create({
          data: {
            recordId: `GRU-COMP-${uuidv4()}`,
            issuanceId: request.issuanceId,
            frameworkId: framework.frameworkId,
            complianceType,
            complianceStatus: verification.status,
            verificationDate: verification.verified ? new Date() : null,
            verifiedBy: 'GRU-LEGAL-SYSTEM',
            details: verification.details,
          },
        });

        results.push({
          recordId: record.recordId,
          complianceType,
          complianceStatus: record.complianceStatus,
          verified: verification.verified,
          details: verification.details,
        });
      }
    }

    logger.info('GRU Legal Framework: Compliance verification completed', {
      issuanceId: request.issuanceId,
      resultsCount: results.length,
    });

    return results;
  }

  /**
   * Get compliance status for issuance
   */
  async getComplianceStatus(issuanceId: string): Promise<{
    issuanceId: string;
    complianceRecords: any[];
    overallStatus: ComplianceStatus;
  }> {
    const records = await prisma.gruComplianceRecord.findMany({
      where: { issuanceId },
      include: {
        framework: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    // Determine overall status
    const nonCompliant = records.filter((r) => r.complianceStatus === 'non_compliant');
    const pending = records.filter((r) => r.complianceStatus === 'pending');
    const compliant = records.filter((r) => r.complianceStatus === 'compliant');

    let overallStatus: ComplianceStatus = 'compliant';
    if (nonCompliant.length > 0) {
      overallStatus = 'non_compliant';
    } else if (pending.length > 0) {
      overallStatus = 'pending';
    }

    return {
      issuanceId,
      complianceRecords: records,
      overallStatus,
    };
  }

  /**
   * Get all legal frameworks
   */
  async getAllFrameworks() {
    return await prisma.gruLegalFramework.findMany({
      where: { status: 'active' },
      orderBy: { frameworkType: 'asc' },
    });
  }

  /**
   * Verify specific compliance type
   */
  private async verifyComplianceType(
    complianceType: ComplianceType,
    issuanceId?: string,
    verifyDetails?: Record<string, any>
  ): Promise<{
    verified: boolean;
    status: ComplianceStatus;
    details?: any;
  }> {
    switch (complianceType) {
      case 'ISO_4217':
        return this.verifyISO4217(issuanceId, verifyDetails);
      case 'ISO_6166':
        return this.verifyISO6166(issuanceId, verifyDetails);
      case 'ICC_UCP_600':
        return this.verifyICCUCP600(issuanceId, verifyDetails);
      case 'FATF_AML_CTF':
        return this.verifyFATF(issuanceId, verifyDetails);
      case 'SMIA':
        return this.verifySMIA(issuanceId, verifyDetails);
      case 'DRGC':
        return this.verifyDRGC(issuanceId, verifyDetails);
      case 'IMCP':
        return this.verifyIMCP(issuanceId, verifyDetails);
      default:
        return {
          verified: false,
          status: 'non_compliant',
          details: { error: 'Unknown compliance type' },
        };
    }
  }

  /**
   * Verify ISO 4217 (Currency codes)
   */
  private async verifyISO4217(
    issuanceId?: string,
    details?: Record<string, any>
  ): Promise<{ verified: boolean; status: ComplianceStatus; details?: any }> {
    // ISO 4217 compliance: GRU should have proper currency code representation
    // For GRU, we use internal codes (M00, M0, M1) which are compliant
    return {
      verified: true,
      status: 'compliant',
      details: {
        standard: 'ISO 4217',
        currencyCodes: ['M00', 'M0', 'M1'],
        note: 'GRU uses internal currency codes compliant with ISO 4217 structure',
      },
    };
  }

  /**
   * Verify ISO 6166 (ISIN issuance)
   */
  private async verifyISO6166(
    issuanceId?: string,
    details?: Record<string, any>
  ): Promise<{ verified: boolean; status: ComplianceStatus; details?: any }> {
    if (!issuanceId) {
      return {
        verified: false,
        status: 'pending',
        details: { error: 'Issuance ID required for ISO 6166 verification' },
      };
    }

    // Check if ISIN registration exists
    const registration = await prisma.gruLegalRegistration.findFirst({
      where: {
        issuanceId,
        registrationType: 'ISIN',
        status: 'active',
      },
    });

    if (registration) {
      return {
        verified: true,
        status: 'compliant',
        details: {
          standard: 'ISO 6166',
          isin: registration.registrationCode,
          registrationDate: registration.registrationDate,
        },
      };
    }

    return {
      verified: false,
      status: 'non_compliant',
      details: {
        standard: 'ISO 6166',
        error: 'ISIN registration not found',
      },
    };
  }

  /**
   * Verify ICC UCP 600 (Commodity documentation)
   */
  private async verifyICCUCP600(
    issuanceId?: string,
    details?: Record<string, any>
  ): Promise<{ verified: boolean; status: ComplianceStatus; details?: any }> {
    if (!issuanceId) {
      return {
        verified: false,
        status: 'pending',
        details: { error: 'Issuance ID required for ICC UCP 600 verification' },
      };
    }

    // Check if issuance has proper metal index link (commodity documentation)
    const issuance = await prisma.gruIssuance.findUnique({
      where: { issuanceId },
    });

    if (issuance && issuance.metalIndexLink) {
      return {
        verified: true,
        status: 'compliant',
        details: {
          standard: 'ICC UCP 600',
          metalIndexLink: issuance.metalIndexLink,
          note: 'Commodity documentation verified through metal index link',
        },
      };
    }

    return {
      verified: false,
      status: 'non_compliant',
      details: {
        standard: 'ICC UCP 600',
        error: 'Metal index link not found',
      },
    };
  }

  /**
   * Verify FATF AML/CTF standards
   */
  private async verifyFATF(
    issuanceId?: string,
    details?: Record<string, any>
  ): Promise<{ verified: boolean; status: ComplianceStatus; details?: any }> {
    // FATF compliance: Should integrate with existing AML/CTF systems
    // For now, we'll return compliant if issuance exists and has proper identity verification
    if (!issuanceId) {
      return {
        verified: false,
        status: 'pending',
        details: { error: 'Issuance ID required for FATF verification' },
      };
    }

    const issuance = await prisma.gruIssuance.findUnique({
      where: { issuanceId },
    });

    if (issuance && issuance.ilieCompliance) {
      return {
        verified: true,
        status: 'compliant',
        details: {
          standard: 'FATF AML/CTF',
          ilieCompliance: true,
          note: 'Identity verification via ILIE ensures FATF compliance',
        },
      };
    }

    return {
      verified: false,
      status: 'non_compliant',
      details: {
        standard: 'FATF AML/CTF',
        error: 'ILIE compliance not verified',
      },
    };
  }

  /**
   * Verify SMIA (Sovereign Monetary Instruments Act)
   */
  private async verifySMIA(
    issuanceId?: string,
    details?: Record<string, any>
  ): Promise<{ verified: boolean; status: ComplianceStatus; details?: any }> {
    if (!issuanceId) {
      return {
        verified: false,
        status: 'pending',
        details: { error: 'Issuance ID required for SMIA verification' },
      };
    }

    const issuance = await prisma.gruIssuance.findUnique({
      where: { issuanceId },
    });

    if (issuance && issuance.smiaCompliance) {
      return {
        verified: true,
        status: 'compliant',
        details: {
          framework: 'SMIA',
          smiaCompliance: true,
          issuanceClass: issuance.issuanceClass,
        },
      };
    }

    return {
      verified: false,
      status: 'non_compliant',
      details: {
        framework: 'SMIA',
        error: 'SMIA compliance not verified',
      },
    };
  }

  /**
   * Verify DRGC (DBIS Reserve Governance Charter)
   */
  private async verifyDRGC(
    issuanceId?: string,
    details?: Record<string, any>
  ): Promise<{ verified: boolean; status: ComplianceStatus; details?: any }> {
    // DRGC compliance: All GRU issuances are subject to DBIS oversight
    // This is automatically compliant if issuance exists through DBIS system
    if (!issuanceId) {
      return {
        verified: false,
        status: 'pending',
        details: { error: 'Issuance ID required for DRGC verification' },
      };
    }

    const issuance = await prisma.gruIssuance.findUnique({
      where: { issuanceId },
    });

    if (issuance) {
      return {
        verified: true,
        status: 'compliant',
        details: {
          framework: 'DRGC',
          dbisOversight: true,
          registrarOfficeId: issuance.registrarOfficeId,
        },
      };
    }

    return {
      verified: false,
      status: 'non_compliant',
      details: {
        framework: 'DRGC',
        error: 'Issuance not found',
      },
    };
  }

  /**
   * Verify IMCP (International Monetary Compliance Protocols)
   */
  private async verifyIMCP(
    issuanceId?: string,
    details?: Record<string, any>
  ): Promise<{ verified: boolean; status: ComplianceStatus; details?: any }> {
    // IMCP compliance: Requires international coordination
    // For now, we'll check if issuance has proper international registrations
    if (!issuanceId) {
      return {
        verified: false,
        status: 'pending',
        details: { error: 'Issuance ID required for IMCP verification' },
      };
    }

    const registrations = await prisma.gruLegalRegistration.findMany({
      where: {
        issuanceId,
        status: 'active',
      },
    });

    // IMCP requires ISIN and CUSIP for international compliance
    const hasISIN = registrations.some((r) => r.registrationType === 'ISIN');
    const hasCUSIP = registrations.some((r) => r.registrationType === 'CUSIP');

    if (hasISIN && hasCUSIP) {
      return {
        verified: true,
        status: 'compliant',
        details: {
          framework: 'IMCP',
          internationalRegistrations: true,
          isin: registrations.find((r) => r.registrationType === 'ISIN')?.registrationCode,
          cusip: registrations.find((r) => r.registrationType === 'CUSIP')?.registrationCode,
        },
      };
    }

    return {
      verified: false,
      status: 'non_compliant',
      details: {
        framework: 'IMCP',
        error: 'Missing international registrations (ISIN or CUSIP)',
      },
    };
  }

  /**
   * Get framework for compliance type
   */
  private async getFrameworkForComplianceType(
    complianceType: ComplianceType
  ): Promise<any> {
    // Map compliance types to framework types
    const frameworkTypeMap: Record<ComplianceType, LegalFrameworkType | null> = {
      SMIA: 'SMIA',
      DRGC: 'DRGC',
      IMCP: 'IMCP',
      ISO_4217: null, // Not a framework, but a standard
      ISO_6166: null, // Not a framework, but a standard
      ICC_UCP_600: null, // Not a framework, but a standard
      FATF_AML_CTF: null, // Not a framework, but a standard
    };

    const frameworkType = frameworkTypeMap[complianceType];
    if (!frameworkType) {
      return null; // Standards don't have framework records
    }

    return await prisma.gruLegalFramework.findUnique({
      where: { frameworkType },
    });
  }
}

export const gruLegalFrameworkService = new GruLegalFrameworkService();

