// Jurisdictional Law Reviewer Service
// Reviews jurisdictional law compatibility

export interface JurisdictionalLawResult {
  approved: boolean;
  riskScore: number;
  review: {
    jurisdiction: string;
    iruTerm: string;
    governingLaw: string;
    compatibility: string;
    requirements: string[];
  };
  issues: string[];
}

export class JurisdictionalLawReviewer {
  /**
   * Review jurisdictional law
   */
  async review(jurisdiction: string, capacityTier: number): Promise<JurisdictionalLawResult> {
    // Integrate with jurisdictional law database
    const { jurisdictionalLawService } = await import('@/core/iru/compliance/jurisdictional-law.service');
    
    try {
      const lawReview = await jurisdictionalLawService.reviewJurisdictionalLaws(
        jurisdiction,
        'Bank', // institutionalType - would come from inquiry
        'settlement' // activityType - would come from inquiry
      );

      return {
        approved: lawReview.compliant,
        riskScore: lawReview.riskLevel === 'high' ? 100 : lawReview.riskLevel === 'medium' ? 50 : 25,
        review: {
          jurisdiction: lawReview.jurisdiction,
          iruTerm: 'Perpetual (subject to termination rights per local law)',
          governingLaw: `Law of ${jurisdiction} (subject to DBIS minimum standards and international law principles)`,
          compatibility: lawReview.compliant ? 'compatible' : 'incompatible',
          requirements: lawReview.requirements,
        },
        issues: lawReview.restrictions,
      };
    } catch (error) {
      // Fallback to basic validation if service fails
      const issues: string[] = [];
      let approved = true;
      let riskScore = 25; // Default risk score

      // Basic validation
      if (!jurisdiction || jurisdiction.length < 2) {
        approved = false;
        issues.push('Invalid jurisdiction specified');
        riskScore = 100;
      }

      // Check for known incompatible jurisdictions
      try {
        const { jurisdictionalLawService } = await import('@/core/iru/compliance/jurisdictional-law.service');
        const lawDetails = await jurisdictionalLawService.getLawDetails(jurisdiction);
        
        const incompatibleJurisdictions: string[] = 
          lawDetails?.iruCompatibility === 'Incompatible' ? [jurisdiction] : [];
        if (incompatibleJurisdictions.includes(jurisdiction)) {
          approved = false;
          issues.push(`Jurisdiction ${jurisdiction} has incompatible legal framework`);
          riskScore = 100;
        }
      } catch (lawError) {
        // If law service fails, continue with basic validation
        approved = false;
        issues.push('Unable to verify jurisdictional law compatibility');
        riskScore = 100;
      }

      // Determine IRU term based on jurisdiction
      const iruTerm = await this.determineIRUTerm(jurisdiction);
      const governingLaw = await this.determineGoverningLaw(jurisdiction);

      return {
        approved,
        riskScore: Math.min(100, riskScore),
        review: {
          jurisdiction,
          iruTerm,
          governingLaw,
          compatibility: approved ? 'compatible' : 'incompatible',
          requirements: await this.getRequirements(jurisdiction, capacityTier),
        },
        issues,
      };
    }
  }

  /**
   * Determine IRU term based on jurisdiction
   */
  private async determineIRUTerm(jurisdiction: string): Promise<string> {
    // Lookup from database
    const { jurisdictionalLawService } = await import('@/core/iru/compliance/jurisdictional-law.service');
    const lawReview = await jurisdictionalLawService.reviewJurisdictionalLaws(jurisdiction, 'Bank', 'settlement');
    
    // Extract term from law review if available
    // Default: Perpetual with termination rights
    return 'Perpetual (subject to termination rights per local law)';
  }

  /**
   * Determine governing law
   */
  private async determineGoverningLaw(jurisdiction: string): Promise<string> {
    // Lookup from database
    // Default: Local jurisdiction law, subject to DBIS minimum standards
    return `Law of ${jurisdiction} (subject to DBIS minimum standards and international law principles)`;
  }

  /**
   * Get jurisdiction-specific requirements
   */
  private async getRequirements(jurisdiction: string, capacityTier: number): Promise<string[]> {
    const requirements: string[] = [];

    // Lookup from database
    const { jurisdictionalLawService } = await import('@/core/iru/compliance/jurisdictional-law.service');
    const lawReview = await jurisdictionalLawService.reviewJurisdictionalLaws(jurisdiction, 'Bank', 'settlement');
    
    // Add requirements from law review
    requirements.push(...lawReview.requirements);

    // Common requirements
    if (!requirements.includes('Compliance with local banking regulations')) {
      requirements.push('Compliance with local banking regulations');
    }
    if (!requirements.includes('Data protection and privacy compliance')) {
      requirements.push('Data protection and privacy compliance');
    }
    if (!requirements.includes('Audit trail capabilities')) {
      requirements.push('Audit trail capabilities');
    }

    // Tier-specific requirements
    if (capacityTier === 1) {
      requirements.push('Central Bank authorization');
      requirements.push('Sovereign immunity considerations');
    }

    return requirements;
  }
}

export const jurisdictionalLawReviewer = new JurisdictionalLawReviewer();
