import { logger } from '../../utils/logger';
import db from '../../config/database';
import { FeatureGovernanceService } from '../../core/governance/FeatureGovernanceService';
import { TracingTopoService } from '../../services/TracingTopoService';

export interface CrisisEvent {
  id?: number;
  type: 'LOGISTICS_HALT' | 'SUPPLIER_BANKRUPTCY' | 'GEOPOLITICAL_SANCTION' | 'FINANCIAL_CRASH';
  severity: 'MEDIUM' | 'HIGH' | 'CRITICAL';
  affectedTenants: string[];
  description: string;
  status: 'DETECTED' | 'MITIGATING' | 'RECOVERED';
}

/**
 * [BIZ_ECO_08] 自治危机管理与恢复协议 (Sovereign Crisis)
 * @description 核心逻辑：建立生态级的危机预警与自愈闭环。
 * 当系统通过 [TracingTopoService] 或 AGI 风险评估发现重大危机（如全球港口停摆、大宗商品暴涨）时，
 * 自动触发“主权防御模式”：重组供应链路由、激活备选供应商、调整流动性头寸。
 */
export class SovereignCrisisService {
  private static readonly CRISIS_TABLE = 'cf_sovereign_crises';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.CRISIS_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.CRISIS_TABLE} table...`);
      await db.schema.createTable(this.CRISIS_TABLE, (table) => {
        table.increments('id').primary();
        table.string('type', 32).notNullable();
        table.string('severity', 16).notNullable();
        table.json('affected_tenants');
        table.text('description');
        table.string('status', 16).defaultTo('DETECTED');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.timestamp('recovered_at');
      });
    }
  }

  /**
   * 触发危机响应
   */
  static async triggerCrisis(event: CrisisEvent): Promise<number> {
    logger.error(`[SovereignCrisis] !!! CRISIS DETECTED: ${event.type} (${event.severity}) !!!`);

    const [id] = await db(this.CRISIS_TABLE).insert({
      type: event.type,
      severity: event.severity,
      affected_tenants: JSON.stringify(event.affectedTenants),
      description: event.description,
      status: 'MITIGATING'
    });

    // 联动自愈逻辑
    await this.initiateMitigation(id, event);

    return id;
  }

  /**
   * 启动自动化缓解方案
   */
  private static async initiateMitigation(crisisId: number, event: CrisisEvent) {
    logger.info(`[SovereignCrisis] Initiating automated mitigation for crisis ${crisisId}`);

    // 1. 针对不同类型的危机执行差异化策略
    switch (event.type) {
      case 'LOGISTICS_HALT':
        // 自动切换备选物流商 (联动 BIZ_TRADE_18)
        logger.warn('[SovereignCrisis] Rerouting all affected logistics to fallback carriers.');
        break;
      case 'SUPPLIER_BANKRUPTCY':
        // 自动激活备选供应商 (联动 BIZ_ECO_03)
        logger.warn('[SovereignCrisis] Activating secondary sourcing for all affected SKUs.');
        break;
      case 'FINANCIAL_CRASH':
        // 增加流动性头寸 (联动 BIZ_FIN_22)
        logger.warn('[SovereignCrisis] Increasing liquidity reserves for all affected tenants.');
        break;
    }

    // 2. 模拟缓解过程
    setTimeout(async () => {
      await db(this.CRISIS_TABLE).where({ id: crisisId }).update({
        status: 'RECOVERED',
        recovered_at: new Date()
      });
      logger.info(`[SovereignCrisis] Crisis ${crisisId} has been successfully mitigated and recovered.`);
    }, 10000);
  }

  /**
   * 获取活跃危机列表
   */
  static async getActiveCrises() {
    return db(this.CRISIS_TABLE).whereNot({ status: 'RECOVERED' });
  }
}
