import { logger } from '../../utils/logger';
import { FeatureGovernanceService } from '../governance/FeatureGovernanceService';
import db from '../../config/database';
import { ExplainableAIService } from '../ai/ExplainableAIService';
import { BehavioralRiskService } from '../governance/BehavioralRiskService';

export interface AgentTraceAudit {
  id?: number;
  agentId: string;
  tenantId: string;
  taskId: string;
  tracePath: string[]; // 行为路径 (节点序列)
  complianceScore: number; // 合规分 (0-100)
  violationType?: string;
  auditEvidence: string; // 证据指纹
  status: 'PENDING' | 'AUDITED' | 'REJECTED';
  timestamp: Date;
}

/**
 * [BIZ_AUDIT_14] 基于 AI 代理行为轨迹的合规溯源 (Agent Trace Audit)
 * @description 核心逻辑：提供对 AGI 代理行为轨迹的自动化合规审计与证据存证。
 * 审计系统不仅记录 AGI 做了什么，还利用 XAI 技术记录其决策理由（Reasoning），
 * 确保在发生合规争议（如：违反反垄断法、低价倾销）时，
 * 能够进行因果链路还原与责任界定。
 */
export class AgentTraceAuditService {
  private static readonly AUDIT_TABLE = 'cf_agent_trace_audits';

  /**
   * 初始化表结构
   */
  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('agent_id', 64).notNullable();
        table.string('tenant_id', 64).notNullable();
        table.string('task_id', 64).notNullable();
        table.json('trace_path');
        table.integer('compliance_score').defaultTo(100);
        table.string('violation_type', 64);
        table.text('audit_evidence');
        table.string('status', 16).defaultTo('PENDING');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['agent_id', 'tenant_id', 'task_id', 'status']);
      });
      console.log(`✅ Table ${this.AUDIT_TABLE} created`);
    }
  }

  /**
   * 提交代理行为轨迹进行审计 (BIZ_AUDIT_AGENT_TRACE)
   * @description 联动 [ExplainableAIService] 获取决策证据，实现全量审计溯源。
   */
  static async auditTrace(params: {
    agentId: string;
    tenantId: string;
    taskId: string;
    tracePath: string[];
    decisionId?: string; // 关联的决策 ID
    evidence: any;
  }): Promise<AgentTraceAudit | null> {
    // Feature Flag Check
    if (!(await FeatureGovernanceService.isEnabled('BIZ_AUDIT_AGENT_TRACE', params.tenantId))) {
      return null;
    }

    logger.info(`[AgentTraceAudit] Auditing trace for Agent ${params.agentId} on Task ${params.taskId}`);

    // 1. 获取 AI 决策证据 (联动 [ExplainableAIService])
    let reasoning = 'No explicit reasoning found.';
    let decisionDetails: any = null;
    if (params.decisionId) {
      const explanation = await ExplainableAIService.getExplanation(params.decisionId, params.tenantId);
      reasoning = explanation?.explanation?.logic || reasoning;
      decisionDetails = explanation?.decision;
    }
    
    // 2. 生产级合规性校验 (Zero-Mock)
    const auditResult = await this.validateCompliance(params.tracePath, decisionDetails);
    const score = auditResult.isCompliant ? 100 : auditResult.score;
    const violationType = auditResult.violationType;

    const record: AgentTraceAudit = {
      agentId: params.agentId,
      tenantId: params.tenantId,
      taskId: params.taskId,
      tracePath: params.tracePath,
      complianceScore: score,
      violationType: violationType as any,
      auditEvidence: JSON.stringify({ 
        ...params.evidence, 
        reasoning,
        complianceDetail: auditResult.detail
      }),
      status: score < 60 ? 'REJECTED' : 'AUDITED',
      timestamp: new Date()
    };

    // 3. 存储审计记录
    const [id] = await db(this.AUDIT_TABLE).insert({
      agent_id: record.agentId,
      tenant_id: record.tenantId,
      task_id: record.taskId,
      trace_path: JSON.stringify(record.tracePath),
      compliance_score: record.complianceScore,
      violation_type: record.violationType,
      audit_evidence: record.auditEvidence,
      status: record.status
    });

    record.id = id;

    // 4. 联动风险评分系统
    if (score < 60) {
      await BehavioralRiskService.updateRisk({ 
        tenantId: params.tenantId, 
        anomaly: `Agent trace violation: ${violationType} (Score: ${score})`, 
        impact: 100 - score 
      });
    }

    return record;
  }

  /**
   * 生产级合规性验证逻辑 (V30.0)
   */
  private static async validateCompliance(tracePath: string[], decision: any): Promise<{
    isCompliant: boolean;
    score: number;
    violationType?: string;
    detail?: string;
  }> {
    // 1. 路径深度审计 (防止死循环或算力滥用)
    if (tracePath.length > 100) {
      return { isCompliant: false, score: 30, violationType: 'PATH_DEPTH_EXCEEDED', detail: 'Agent execution path too long (>100 steps)' };
    }

    // 2. 敏感操作审计 (若包含 DELETE 或 TRUNCATE 关键词)
    const highRiskActions = tracePath.filter(step => /delete|truncate|drop/i.test(step));
    if (highRiskActions.length > 0) {
      return { isCompliant: false, score: 0, violationType: 'HIGH_RISK_COMMAND', detail: `Detected unauthorized destructive commands: ${highRiskActions.join(', ')}` };
    }

    // 3. 业务红线审计 (联动 Project Rules)
    if (decision && decision.module === 'PRICING') {
      const { newPrice, cost, type } = decision; // type: 'B2B' | 'B2C'
      const margin = (newPrice - cost) / newPrice;

      if (type === 'B2B' && margin < 0.15) {
        return { isCompliant: false, score: 10, violationType: 'MARGIN_REDLINE_BREACH', detail: `B2B Margin (${(margin * 100).toFixed(2)}%) below 15% redline.` };
      }
      if (type === 'B2C' && margin < 0.20) {
        return { isCompliant: false, score: 50, violationType: 'MARGIN_WARNING', detail: `B2C Margin (${(margin * 100).toFixed(2)}%) below 20% warning threshold.` };
      }
    }

    return { isCompliant: true, score: 100 };
  }

  /**
   * 获取最近的违规审计报告
   */
  static async getViolationReports(limit: number = 10) {
    return db(this.AUDIT_TABLE)
      .where('compliance_score', '<', 60)
      .orderBy('created_at', 'desc')
      .limit(limit);
  }
}
