import * as crypto from 'crypto';
import { logger } from '../../utils/logger';
import { FeatureGovernanceService } from '../governance/FeatureGovernanceService';
import db from '../../config/database';
import { ProofOfComputationService, ComputationProof } from './ProofOfComputationService';

export interface EnclaveConfig {
  tenantId: string;
  enclaveType: 'INTEL_SGX' | 'AMD_SEV' | 'ARM_TRUSTZONE';
  measurementHash: string;
}

export interface TEEChainRecord {
  id?: number;
  tenant_id: string;
  task_name: string;
  proof_id: string;
  enclave_type: string;
  attestation_report: string;
  status: string;
  created_at?: Date;
}

/**
 * [CORE_SEC_15] 基于硬件隔离的受限计算证明链 (TEE Proof Chain / Hardware Enclave)
 * @description 核心逻辑：支持在受信任执行环境 (TEE) 中执行敏感代码，并生成不可篡改的证明链。
 * 扩展 [CORE_SEC_12] 的基础硬件隔离能力，集成 [CORE_SEC_14] 的计算证明，形成持久化的审计链。
 */
export class HardwareEnclaveService {
  private static readonly TEE_CHAIN_TABLE = 'cf_tee_proof_chain';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.TEE_CHAIN_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.TEE_CHAIN_TABLE} table...`);
      await db.schema.createTable(this.TEE_CHAIN_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable().index();
        table.string('task_name', 128).notNullable();
        table.string('proof_id', 128).notNullable().unique();
        table.string('enclave_type', 32).notNullable();
        table.text('attestation_report').notNullable(); // 存储加密签名的报告
        table.string('status', 32).defaultTo('VERIFIED');
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
      logger.info(`✅ Table ${this.TEE_CHAIN_TABLE} created`);
    }
  }

  /**
   * 启动受保护的 Enclave 任务并生成证明链
   */
  static async runProtectedTask(taskName: string, payload: any, config: EnclaveConfig): Promise<any> {
    // Feature Flag Check
    if (!(await FeatureGovernanceService.isEnabled('CORE_SEC_HARDWARE_ENCLAVE', config.tenantId))) {
      logger.warn(`[HardwareEnclave] Enclave task ${taskName} skipped: Feature disabled for Tenant ${config.tenantId}`);
      return payload; // 降级到常规不安全执行
    }

    logger.info(`[HardwareEnclave] Launching TEE task ${taskName} for Tenant ${config.tenantId} using ${config.enclaveType}`);

    try {
      // 1. 模拟远程验证 (Remote Attestation)
      const isVerified = await this.verifyEnclaveIntegrity(config.measurementHash);
      if (!isVerified) throw new Error('Enclave integrity verification failed: Measurement hash mismatch.');

      // 2. 模拟加密数据注入与解密
      const encryptedInput = this.encryptForEnclave(payload);
      
      // 3. 模拟 Enclave 内部执行
      const rawResult = this.executeInEnclave(taskName, encryptedInput);
      
      // 4. 生成计算证明 (Proof of Computation - CORE_SEC_14)
      const proof: ComputationProof = ProofOfComputationService.generateProof(payload, rawResult, `tee-node-${config.enclaveType}`);
      
      // 5. 模拟结果签名 (Attestation Report)
      const attestationReport = crypto.createHmac('sha256', process.env.TEE_SECRET || 'hardware-root-key')
        .update(JSON.stringify({ result: rawResult, proofId: proof.proofId, measurement: config.measurementHash }))
        .digest('hex');
      
      // 6. 持久化到证明链表 (CORE_SEC_15)
      await db(this.TEE_CHAIN_TABLE).insert({
        tenant_id: config.tenantId,
        task_name: taskName,
        proof_id: proof.proofId,
        enclave_type: config.enclaveType,
        attestation_report: attestationReport,
        status: 'VERIFIED'
      });

      logger.info(`[HardwareEnclave] TEE Task ${taskName} completed and proof chain updated: ${proof.proofId}`);
      
      return { 
        result: rawResult, 
        proofId: proof.proofId,
        attestation: attestationReport, 
        status: 'ENCLAVE_VERIFIED' 
      };
    } catch (err: any) {
      logger.error(`[HardwareEnclave] TEE Task failed: ${err.message}`);
      throw err;
    }
  }

  /**
   * 模拟完整性校验
   */
  private static async verifyEnclaveIntegrity(hash: string): Promise<boolean> {
    const knownGoodHashes = ['v1.0.0_sgx_stable', 'v1.1.0_sev_active', 'v2.0.0_tee_master'];
    return knownGoodHashes.includes(hash);
  }

  /**
   * 模拟 TEE 加密信道
   */
  private static encryptForEnclave(data: any): string {
    return Buffer.from(JSON.stringify(data)).toString('base64');
  }

  /**
   * 模拟 Enclave 内部执行环境
   */
  private static executeInEnclave(task: string, inputB64: string): any {
    const input = JSON.parse(Buffer.from(inputB64, 'base64').toString('utf-8'));
    
    // 敏感逻辑：如利润率红线强制校验 (V22.0)
    if (task === 'MARGIN_AUDIT') {
      const margin = (input.sellingPrice - input.costPrice) / input.sellingPrice;
      // 利润率红线：B2B < 15% 禁止放行
      return { margin, isCompliant: margin >= 0.15, policy: 'B2B_MARGIN_15' };
    }

    if (task === 'CREDIT_LIMIT_DECISION') {
      // 敏感授信逻辑：基于信用分与历史流水
      const limit = input.creditScore * 100 + input.avgTurnover * 0.1;
      return { approvedLimit: limit, riskLevel: input.creditScore > 80 ? 'LOW' : 'MEDIUM' };
    }

    return { ...input, status: 'PROCESSED_IN_TEE', processedAt: new Date() };
  }

  /**
   * 获取租户的 TEE 审计链
   */
  static async getProofChain(tenantId: string): Promise<TEEChainRecord[]> {
    return db(this.TEE_CHAIN_TABLE)
      .where({ tenant_id: tenantId })
      .orderBy('created_at', 'desc');
  }
}
