import { logger } from '../../utils/logger';
import { FeatureGovernanceService } from '../governance/FeatureGovernanceService';
import db from '../../config/database';
import { ZKPQualificationService } from './ZKPQualificationService';
import { ProofOfComputationService } from './ProofOfComputationService';
import crypto from 'crypto';

export interface AuditRecord {
  id?: number;
  tenantId: string;
  auditType: 'FINANCIAL' | 'TRADE' | 'COMPLIANCE';
  zkpProof: string; // 零知识证明
  verificationHash: string; // 验证哈希
  status: 'PENDING' | 'VERIFIED' | 'FAILED';
  auditorId?: string;
  timestamp: Date;
}

/**
 * [CORE_SEC_20 / BIZ_SEC_01] 基于零知识证明的全流程隐私审计 (Private Audit)
 * @description 核心逻辑：支持在完全不泄露业务明文的前提下，向外部审计方提供业务真实性证明。
 * 实现 ZKP 基础设施，支持“证明范围”审计 (Range Proof)。
 */
export class PrivateAuditService {
  private static readonly AUDIT_TABLE = 'cf_private_audit_records';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.AUDIT_TABLE);
    if (!hasTable) {
      console.log(`📦 Creating ${this.AUDIT_TABLE} table...`);
      await db.schema.createTable(this.AUDIT_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('audit_type', 32).notNullable();
        table.text('zkp_proof').notNullable();
        table.string('verification_hash', 128).notNullable().unique();
        table.string('status', 16).defaultTo('PENDING');
        table.string('auditor_id', 64);
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.timestamp('updated_at').defaultTo(db.fn.now());
        table.index(['tenant_id', 'audit_type', 'status']);
      });
      console.log(`✅ Table ${this.AUDIT_TABLE} created`);
    }
  }

  /**
   * 生成隐私审计证明 (Enhanced for BIZ_SEC_01)
   * @description 模拟 Range Proof：证明 SensitiveData > Threshold
   */
  static async generateAuditProof(params: {
    tenantId: string;
    auditType: AuditRecord['auditType'];
    sensitiveData: number; // 敏感数值，如利润率
    threshold: number;    // 阈值，如 0.15 (15%)
  }): Promise<AuditRecord | null> {
    if (!(await FeatureGovernanceService.isEnabled('CORE_SEC_PRIVATE_AUDIT', params.tenantId))) {
      return null;
    }

    logger.info(`[PrivateAudit] Generating ${params.auditType} proof for Tenant: ${params.tenantId}`);

    try {
      // 1. 模拟 ZKP Range Proof 生成
      // 如果满足条件，生成有效证明；否则生成无效证明
      const isSatisfied = params.sensitiveData >= params.threshold;
      
      // 生成一个带有业务逻辑绑定的证明 Hash
      const salt = crypto.randomBytes(16).toString('hex');
      const commitment = crypto.createHash('sha256')
        .update(`${params.tenantId}:${params.auditType}:${params.threshold}:${salt}`)
        .digest('hex');

      const proof = JSON.stringify({
        version: 'zkp-v2',
        commitment,
        satisfied: isSatisfied,
        type: 'RANGE_PROOF',
        threshold: params.threshold,
        timestamp: Date.now()
      });
      
      // 2. 生成验证哈希 (用于索引和存证)
      const verificationHash = crypto.createHash('sha256')
        .update(proof)
        .digest('hex');

      const record: AuditRecord = {
        tenantId: params.tenantId,
        auditType: params.auditType,
        zkpProof: proof,
        verificationHash: verificationHash,
        status: 'PENDING',
        timestamp: new Date()
      };

      await db(this.AUDIT_TABLE).insert({
        tenant_id: record.tenantId,
        audit_type: record.auditType,
        zkp_proof: record.zkpProof,
        verification_hash: record.verificationHash,
        status: record.status
      });

      // 3. 联动计算证明链 (CORE_SEC_14)
      await ProofOfComputationService.registerProof(verificationHash, 'ZKP_GENERATION_SUCCESS');

      return record;
    } catch (err: any) {
      logger.error(`[PrivateAudit] Failed to generate audit proof: ${err.message}`);
      throw err;
    }
  }

  /**
   * 验证隐私审计证明 (供第三方审计调用)
   */
  static async verifyProof(verificationHash: string, auditorId: string): Promise<boolean> {
    logger.info(`[PrivateAudit] Auditor ${auditorId} verifying proof: ${verificationHash}`);

    try {
      const record = await db(this.AUDIT_TABLE).where({ verification_hash: verificationHash }).first();
      if (!record) {
        throw new Error('Audit record not found');
      }

      // 1. 调用 ZKP 验证引擎 (Actual: Verify ZK-SNARK/STARK proof)
      const isValid = await ZKPQualificationService.verifyProof(record.zkp_proof);

      if (isValid) {
        await db(this.AUDIT_TABLE).where({ verification_hash: verificationHash }).update({
          status: 'VERIFIED',
          auditor_id: auditorId,
          updated_at: new Date()
        });
        
        // 2. 注册到计算证明链 (CORE_SEC_14)
        await ProofOfComputationService.registerProof(verificationHash, 'ZKP_AUDIT_SUCCESS');
      } else {
        await db(this.AUDIT_TABLE).where({ verification_hash: verificationHash }).update({
          status: 'FAILED',
          updated_at: new Date()
        });
      }

      return isValid;
    } catch (err: any) {
      logger.error(`[PrivateAudit] Verification failed: ${err.message}`);
      throw err;
    }
  }

  /**
   * 获取租户所有审计记录
   */
  static async getTenantAuditHistory(tenantId: string): Promise<AuditRecord[]> {
    return db(this.AUDIT_TABLE).where({ tenant_id: tenantId }).orderBy('created_at', 'desc');
  }
}
