// DCDC Defense Layers Orchestration
// Unified Layer A-D orchestration (Detection, Containment, Neutralization, Restoration)

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { dcdcOperationalDefenseService } from './dcdc-operational-defense.service';
import { dcdcForensicsService } from './dcdc-forensics.service';
import { dcdcCounterIntrusionService } from './dcdc-counter-intrusion.service';
import { sovereignGraphSecurityService } from './sovereign-graph-security.service';


export interface LayerAction {
  layer: string;
  actionType: string;
  actionId: string;
  status: string;
  executedAt: Date;
}

export interface DefenseResponse {
  incidentId: string;
  layers: LayerAction[];
  status: string;
  completedAt?: Date;
}

export class DefenseLayersService {
  /**
   * Execute full defense layer sequence
   */
  async executeDefenseSequence(
    incidentId: string,
    threatType: string,
    severity: string,
    targetNodeId?: string,
    targetBankId?: string
  ): Promise<DefenseResponse> {
    const layers: LayerAction[] = [];

    // Layer A - Detection
    const detectionAction = await this.executeLayerA(incidentId, threatType, severity);
    layers.push(detectionAction);

    // Layer B - Containment
    if (severity === 'high' || severity === 'critical') {
      const containmentAction = await this.executeLayerB(incidentId, targetNodeId, targetBankId);
      layers.push(containmentAction);
    }

    // Layer C - Neutralization
    if (severity === 'critical') {
      const neutralizationAction = await this.executeLayerC(incidentId, threatType, targetNodeId);
      layers.push(neutralizationAction);
    }

    // Layer D - Restoration
    if (severity === 'critical') {
      const restorationAction = await this.executeLayerD(incidentId);
      layers.push(restorationAction);
    }

    const allCompleted = layers.every((layer) => layer.status === 'executed');
    const status = allCompleted ? 'completed' : 'in_progress';

    return {
      incidentId,
      layers,
      status,
      completedAt: allCompleted ? new Date() : undefined,
    };
  }

  /**
   * Layer A - Detection
   */
  async executeLayerA(
    incidentId: string,
    threatType: string,
    severity: string
  ): Promise<LayerAction> {
    // Use SGSE for detection
    const detectionResult = await sovereignGraphSecurityService.detectAnomaly(
      threatType,
      severity
    );

    const action = await prisma.defense_layer_actions.create({
      data: {
        actionId: `LAYER-A-${uuidv4()}`,
        incidentId,
        layer: 'A',
        actionType: detectionResult.detectionMethod,
        description: `Layer A Detection: ${threatType}`,
        actionStatus: 'executed',
        metadata: {
          detectionResult,
        },
        executedAt: new Date(),
      },
    });

    return {
      layer: 'A',
      actionType: action.actionType,
      actionId: action.actionId,
      status: action.actionStatus,
      executedAt: action.executedAt || new Date(),
    };
  }

  /**
   * Layer B - Containment
   */
  async executeLayerB(
    incidentId: string,
    targetNodeId?: string,
    targetBankId?: string
  ): Promise<LayerAction> {
    // Use ODU for containment
    await dcdcOperationalDefenseService.respondToAttack(incidentId, 'containment', targetNodeId, targetBankId);

    const action = await prisma.defense_layer_actions.create({
      data: {
        actionId: `LAYER-B-${uuidv4()}`,
        incidentId,
        layer: 'B',
        actionType: 'route_isolation',
        targetNodeId,
        targetBankId,
        description: 'Layer B Containment: Route isolation and node quarantine',
        actionStatus: 'executed',
        executedAt: new Date(),
      },
    });

    return {
      layer: 'B',
      actionType: action.actionType,
      actionId: action.actionId,
      status: action.actionStatus,
      executedAt: action.executedAt || new Date(),
    };
  }

  /**
   * Layer C - Neutralization
   */
  async executeLayerC(
    incidentId: string,
    threatType: string,
    targetNodeId?: string
  ): Promise<LayerAction> {
    // Use ODU or CIST for neutralization
    let actionType = 'kill_switch';
    if (threatType.includes('intrusion')) {
      await dcdcCounterIntrusionService.handleHighSeverityThreat(incidentId, threatType, targetNodeId ? [targetNodeId] : []);
      actionType = 'counter_intrusion';
    } else {
      await dcdcOperationalDefenseService.executeCountermeasures(incidentId, 'kill_switch');
    }

    const action = await prisma.defense_layer_actions.create({
      data: {
        actionId: `LAYER-C-${uuidv4()}`,
        incidentId,
        layer: 'C',
        actionType,
        targetNodeId,
        description: `Layer C Neutralization: ${actionType}`,
        actionStatus: 'executed',
        executedAt: new Date(),
      },
    });

    return {
      layer: 'C',
      actionType: action.actionType,
      actionId: action.actionId,
      status: action.actionStatus,
      executedAt: action.executedAt || new Date(),
    };
  }

  /**
   * Layer D - Restoration
   */
  async executeLayerD(incidentId: string): Promise<LayerAction> {
    // Use FRB for restoration
    await dcdcForensicsService.performForensicAnalysis(
      incidentId,
      'restoration',
      {},
      []
    );

    const action = await prisma.defense_layer_actions.create({
      data: {
        actionId: `LAYER-D-${uuidv4()}`,
        incidentId,
        layer: 'D',
        actionType: 'meta_ledger_rollback',
        description: 'Layer D Restoration: Meta-ledger rollback and deterministic reconstruction',
        actionStatus: 'executed',
        executedAt: new Date(),
      },
    });

    return {
      layer: 'D',
      actionType: action.actionType,
      actionId: action.actionId,
      status: action.actionStatus,
      executedAt: action.executedAt || new Date(),
    };
  }

  /**
   * Get defense layer actions for incident
   */
  async getDefenseActions(incidentId: string) {
    return await prisma.defense_layer_actions.findMany({
      where: { incidentId },
      orderBy: [
        { layer: 'asc' },
        { executedAt: 'asc' },
      ],
    });
  }
}

export const defenseLayersService = new DefenseLayersService();

