// ARI Decisioning Service
import { Prisma } from '@prisma/client';
// Decision engine: if SARE.FXSP > 0.35: tighten_FX_band(SCB), reduce_liquidity_limit(SCB)

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { logger } from '@/infrastructure/monitoring/logger';
import { ariCortexService } from './ari-cortex.service';
import { ariReflexService } from './ari-reflex.service';
import { ariExecutionService } from './ari-execution.service';


export interface DecisioningRequest {
  sovereignBankId: string;
  triggerCondition: string;
}

export class AriDecisioningService {
  /**
   * Make autonomous regulatory decision
   */
  async makeDecision(request: DecisioningRequest): Promise<{ decisionId: string; actions: string[] }> {
    const decisionId = `ARI-DECISION-${uuidv4()}`;

    // Get risk predictions from Cortex
    const riskPredictions = await ariCortexService.predictRisk(request.sovereignBankId);

    // Evaluate trigger conditions
    const actions: string[] = [];

    // Example: if SARE.FXSP > 0.35: tighten_FX_band(SCB), reduce_liquidity_limit(SCB)
    if (riskPredictions.fxShockProbability > 0.35) {
      // Tighten FX band
      await ariReflexService.adjustFxBand(request.sovereignBankId, riskPredictions.fxShockProbability);
      actions.push('tighten_fx_band');

      // Reduce liquidity limit
      await this.reduceLiquidityLimit(request.sovereignBankId);
      actions.push('reduce_liquidity_limit');

      // Create decision record
      await prisma.ari_decisions.create({
        data: {
          id: uuidv4(),
          decisionId,
          decisionType: 'fx_band_adjustment',
          targetSystem: 'fx_engine',
          decisionData: {
            triggerCondition: `FXSP > 0.35 (actual: ${riskPredictions.fxShockProbability})`,
            actions: ['tighten_fx_band', 'reduce_liquidity_limit'],
            fxShockProbability: riskPredictions.fxShockProbability,
          } as Prisma.InputJsonValue,
          triggerCondition: request.triggerCondition || `SARE.FXSP > 0.35`,
          status: 'pending',
          createdAt: new Date(),
          updatedAt: new Date(),
        },
      });

      logger.info('ARI Decisioning: Decision made', {
        decisionId,
        sovereignBankId: request.sovereignBankId,
        actions,
        triggerCondition: `FXSP > 0.35 (${riskPredictions.fxShockProbability})`,
      });
    }

    // Check liquidity tension
    if (riskPredictions.liquidityTension > 70) {
      await this.adjustLiquidityPolicy(request.sovereignBankId, riskPredictions.liquidityTension);
      actions.push('adjust_liquidity_policy');

      await prisma.ari_decisions.create({
        data: {
          id: uuidv4(),
          decisionId: `ARI-DECISION-${uuidv4()}`,
          decisionType: 'liquidity_limit_change',
          targetSystem: 'alps',
          decisionData: {
            liquidityTension: riskPredictions.liquidityTension,
            action: 'adjust_liquidity_policy',
          } as Prisma.InputJsonValue,
          triggerCondition: `Liquidity tension > 70 (actual: ${riskPredictions.liquidityTension})`,
          status: 'pending',
          createdAt: new Date(),
          updatedAt: new Date(),
        },
      });
    }

    return { decisionId, actions };
  }

  /**
   * Reduce liquidity limit
   */
  private async reduceLiquidityLimit(sovereignBankId: string): Promise<void> {
    // In production, would call ALPS service to reduce liquidity limit
    logger.info('ARI Decisioning: Liquidity limit reduced', { sovereignBankId });
  }

  /**
   * Adjust liquidity policy
   */
  private async adjustLiquidityPolicy(sovereignBankId: string, liquidityTension: number): Promise<void> {
    // Get current liquidity policy
    const currentPolicy = await prisma.ari_policies.findFirst({
      where: {
        policyType: 'liquidity',
        status: 'active',
        layer: 'reflex',
      },
      orderBy: { effectiveDate: 'desc' },
    });

    if (currentPolicy) {
      const rules = currentPolicy.policyRules as unknown as Record<string, unknown>;
      const newInterventionThreshold = (rules.interventionThreshold as number) * 0.9; // Reduce by 10%

      await prisma.ari_policy_updates.create({
        data: {
          id: uuidv4(),
          updateId: `ARI-UPDATE-${uuidv4()}`,
          policyId: currentPolicy.policyId,
          updateType: 'modification',
          previousRules: currentPolicy.policyRules as Prisma.InputJsonValue,
          newRules: {
            ...rules,
            interventionThreshold: newInterventionThreshold,
          } as Prisma.InputJsonValue,
          reason: `Liquidity policy adjusted due to high tension: ${liquidityTension}`,
          updatedBy: 'ari',
          status: 'approved',
          createdAt: new Date(),
          updatedAt: new Date(),
        },
      });

      await prisma.ari_policies.update({
        where: { policyId: currentPolicy.policyId },
        data: {
          policyRules: {
            ...rules,
            interventionThreshold: newInterventionThreshold,
          } as Prisma.InputJsonValue,
        },
      });
    }
  }
}

export const ariDecisioningService = new AriDecisioningService();

