// Legal Harmonization Service - Pillar II

import prisma from '@/shared/database/prisma';
import { HarmonizationPillar } from './types';
import { logger } from '@/infrastructure/monitoring/logger';


export class LegalHarmonizationService {
  /**
   * Get legal harmonization rules
   */
  async getRules() {
    return prisma.regulatory_harmonization_rules.findMany({
      where: { pillar: HarmonizationPillar.LEGAL },
      orderBy: { ruleCode: 'asc' },
    });
  }

  /**
   * Initialize default legal harmonization rules
   */
  async initializeDefaultRules(): Promise<void> {
    const rules = [
      {
        pillar: HarmonizationPillar.LEGAL,
        ruleCode: 'SETTLEMENT_LAW',
        name: 'Standardized Settlement Law',
        description: 'Unified settlement law across all sovereigns',
        requirements: [
          'Adopt DBIS Settlement Law Codebook',
          'Recognize finality and irrevocability principles',
          'Implement multilateral recognition',
        ],
        status: 'ACTIVE' as const,
      },
      {
        pillar: HarmonizationPillar.LEGAL,
        ruleCode: 'ARBITRATION_ENFORCEMENT',
        name: 'Unified Arbitration and Enforcement',
        description: 'Standardized dispute resolution and enforcement',
        requirements: [
          'Participate in DBIS International Arbitration (DIAS)',
          'Accept binding arbitration decisions',
          'Implement automated enforcement',
        ],
        status: 'ACTIVE' as const,
      },
      {
        pillar: HarmonizationPillar.LEGAL,
        ruleCode: 'CROSS_BORDER_RECOGNITION',
        name: 'Cross-Border Recognition of DBIS Authority',
        description: 'Recognition of DBIS legal authority across borders',
        requirements: [
          'Recognize DBIS governance decisions',
          'Accept DBIS regulatory equivalence',
          'Implement cross-border legal cooperation',
        ],
        status: 'ACTIVE' as const,
      },
    ];

    for (const rule of rules) {
      await prisma.regulatory_harmonization_rules.upsert({
        where: {
          pillar_ruleCode: {
            pillar: rule.pillar,
            ruleCode: rule.ruleCode,
          },
        },
        create: {
          id: `GRHS-${rule.pillar}-${rule.ruleCode}`,
          ...rule,
          applicableSovereigns: [],
          createdAt: new Date(),
          updatedAt: new Date(),
        },
        update: {
          name: rule.name,
          description: rule.description,
          requirements: rule.requirements,
          status: rule.status,
        },
      });
    }

    logger.info('Initialized legal harmonization rules');
  }

  /**
   * Assess compliance with legal harmonization
   */
  async assessCompliance(sovereignBankId: string): Promise<number> {
    const rules = await this.getRules();
    let compliantCount = 0;

    for (const rule of rules) {
      const isCompliant = await this.checkRuleCompliance(sovereignBankId, rule.ruleCode);
      if (isCompliant) {
        compliantCount++;
      }
    }

    return rules.length > 0 ? (compliantCount / rules.length) * 100 : 0;
  }

  /**
   * Check compliance with a specific rule
   */
  private async checkRuleCompliance(sovereignBankId: string, ruleCode: string): Promise<boolean> {
    // Simplified compliance check
    switch (ruleCode) {
      case 'SETTLEMENT_LAW':
        // Check if sovereign participates in settlement
        const settlements = await prisma.atomic_settlements.findFirst({
          where: {
            OR: [
              { sourceBankId: sovereignBankId },
              { destinationBankId: sovereignBankId },
            ],
          },
        });
        return !!settlements;
      case 'ARBITRATION_ENFORCEMENT':
        // Check if sovereign has arbitration records
        const arbitrations = await prisma.dispute_resolutions.findFirst({
          where: {
            OR: [
              { sovereignBankId1: sovereignBankId },
              { sovereignBankId2: sovereignBankId },
            ],
          },
        });
        return !!arbitrations;
      case 'CROSS_BORDER_RECOGNITION':
        // Check if sovereign is active
        const sovereignBank = await prisma.sovereign_banks.findUnique({
          where: { id: sovereignBankId },
        });
        return sovereignBank?.status === 'active';
      default:
        return false;
    }
  }
}

export const legalHarmonizationService = new LegalHarmonizationService();

