import { logger } from '../../utils/logger';
import { FeatureGovernanceService } from '../governance/FeatureGovernanceService';
import db from '../../config/database';
import { HardwareEnclaveService } from './HardwareEnclaveService';

export interface KillSwitchStatus {
  tenantId: string;
  isActivated: boolean;
  reason?: string;
  activatedAt?: Date;
  severity: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
}

/**
 * [CORE_SEC_21] 针对 AGI 恶意演化的硬核熔断机制 (AGI Kill-Switch)
 * @description 核心逻辑：建立物理/逻辑级隔离的 AI 行为准则门禁。
 * 当检测到 AGI 代理出现非预期演化（如绕过安全限制、尝试非法越权、产生严重幻觉）时，
 * 能够瞬间强制关停该租户或全局的 AGI 推理引擎。
 */
export class AGIKillSwitchService {
  private static readonly STATUS_TABLE = 'cf_agi_kill_switches';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.STATUS_TABLE);
    if (!hasTable) {
      console.log(`📦 Creating ${this.STATUS_TABLE} table...`);
      await db.schema.createTable(this.STATUS_TABLE, (table) => {
        table.string('tenant_id', 64).primary();
        table.boolean('is_activated').defaultTo(false);
        table.string('reason', 256);
        table.string('severity', 16);
        table.timestamp('activated_at');
        table.timestamps(true, true);
      });
      console.log(`✅ Table ${this.STATUS_TABLE} created`);
    }
  }

  /**
   * 激活熔断机制
   */
  static async activate(tenantId: string, reason: string, severity: KillSwitchStatus['severity'] = 'HIGH') {
    logger.error(`[AGIKillSwitch] ACTIVATING KILL-SWITCH for Tenant: ${tenantId}. Reason: ${reason}`);

    await db(this.STATUS_TABLE)
      .insert({
        tenant_id: tenantId,
        is_activated: true,
        reason,
        severity,
        activated_at: new Date()
      })
      .onConflict('tenant_id')
      .merge();

    // 联动 TEE 硬件隔离层进行物理级隔离 (模拟)
    await HardwareEnclaveService.runProtectedTask('AGI_HARD_STOP', { tenantId }, {
      tenantId,
      enclaveType: 'INTEL_SGX',
      measurementHash: 'AGI_KILL_SIG_0x7f'
    });

    // 异步清除相关 AGI 节点的缓存与运行状态
    // await AgentSwarmService.broadcastKillSignal(tenantId);
  }

  /**
   * 检查租户是否已被熔断
   */
  static async isBroken(tenantId: string): Promise<boolean> {
    const status = await db(this.STATUS_TABLE).where({ tenant_id: tenantId }).first();
    return status?.is_activated || false;
  }

  /**
   * 解除熔断 (需要高级管理员权限)
   */
  static async deactivate(tenantId: string) {
    await db(this.STATUS_TABLE)
      .where({ tenant_id: tenantId })
      .update({ is_activated: false, reason: null, severity: null, activated_at: null });
    
    logger.info(`[AGIKillSwitch] Kill-switch deactivated for Tenant: ${tenantId}`);
  }
}
