// DBIS Admin Console - Risk & Compliance Service
// SARE, ARI, Ω-Layer consistency

import prisma from '@/shared/database/prisma';
import { logger } from '@/infrastructure/monitoring/logger';
import { dashboardService } from '@/core/compliance/regtech/dashboard.service';

export interface SARERiskHeatmap {
  scbId: string;
  scbName: string;
  riskScore: number;
  riskLevel: 'low' | 'medium' | 'high' | 'critical';
  factors: Array<{
    factor: string;
    score: number;
  }>;
}

export interface ARIAlert {
  alertId: string;
  type: string;
  severity: 'low' | 'medium' | 'high' | 'critical';
  description: string;
  scbId?: string;
  timestamp: Date;
  status: 'new' | 'acknowledged' | 'under_investigation' | 'resolved';
}

export interface OmegaLayerIncident {
  incidentId: string;
  type: string;
  severity: string;
  description: string;
  affectedSCBs: string[];
  timestamp: Date;
  status: 'active' | 'resolved';
}

export interface RiskComplianceDashboard {
  sareHeatmap: SARERiskHeatmap[];
  ariAlerts: ARIAlert[];
  omegaLayerIncidents: OmegaLayerIncident[];
}

export class RiskComplianceService {
  /**
   * Get Risk & Compliance dashboard
   */
  async getRiskComplianceDashboard(): Promise<RiskComplianceDashboard> {
    const [sareHeatmap, ariAlerts, omegaLayerIncidents] = await Promise.all([
      this.getSAREHeatmap(),
      this.getARIAlerts(),
      this.getOmegaLayerIncidents(),
    ]);

    return { sareHeatmap, ariAlerts, omegaLayerIncidents };
  }

  /**
   * Get SARE sovereign risk heatmap
   */
  async getSAREHeatmap(): Promise<SARERiskHeatmap[]> {
    const scbs = await prisma.sovereignBank.findMany({
      where: { status: 'active' },
    });

    const heatmap: SARERiskHeatmap[] = [];

    for (const scb of scbs) {
      // Get latest SRI
      const sri = await prisma.sovereignRiskIndex.findFirst({
        where: { sovereignBankId: scb.id },
        orderBy: { calculatedAt: 'desc' },
      });

      const riskScore = sri ? parseFloat(sri.sriScore.toString()) : 0;
      let riskLevel: 'low' | 'medium' | 'high' | 'critical' = 'low';
      if (riskScore >= 60) riskLevel = 'critical';
      else if (riskScore >= 40) riskLevel = 'high';
      else if (riskScore >= 20) riskLevel = 'medium';

      heatmap.push({
        scbId: scb.id,
        scbName: scb.name,
        riskScore,
        riskLevel,
        factors: [
          { factor: 'liquidity', score: riskScore * 0.3 },
          { factor: 'fx_stability', score: riskScore * 0.25 },
          { factor: 'cbdc_health', score: riskScore * 0.25 },
          { factor: 'commodity_exposure', score: riskScore * 0.2 },
        ],
      });
    }

    return heatmap.sort((a, b) => b.riskScore - a.riskScore);
  }

  /**
   * Get ARI regulatory alerts
   */
  async getARIAlerts(): Promise<ARIAlert[]> {
    // Get incident alerts from dashboard service
    const dashboard = await dashboardService.getIncidentAlertsDashboard();
    const alerts = dashboard.incidentAlerts || [];

    return alerts.map((alert, index) => ({
      alertId: `ari-${index}`,
      type: alert.type,
      severity: alert.severity as 'low' | 'medium' | 'high' | 'critical',
      description: alert.description,
      timestamp: alert.timestamp,
      status: 'new' as const,
    }));
  }

  /**
   * Get Ω-Layer consistency incidents
   */
  async getOmegaLayerIncidents(): Promise<OmegaLayerIncident[]> {
    // Placeholder - would integrate with actual Ω-Layer monitoring
    // Check for settlement inconsistencies
    const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);

    const failedSettlements = await prisma.atomicSettlement.findMany({
      where: {
        status: 'failed',
        createdAt: { gte: oneDayAgo },
      },
      take: 10,
    });

    return failedSettlements.map((settlement) => ({
      incidentId: settlement.settlementId,
      type: 'settlement_failure',
      severity: 'high',
      description: `Settlement ${settlement.settlementId} failed`,
      affectedSCBs: [settlement.sourceBankId, settlement.destinationBankId],
      timestamp: settlement.createdAt,
      status: 'active' as const,
    }));
  }
}

export const riskComplianceService = new RiskComplianceService();

