import db from '../config/database';
import { AuditService } from './AuditService';
import { AIService } from './AIService';

/**
 * [BIZ_SOV_04] 自治贸易主权合规治理引擎 (Sovereignty Governance)
 * 负责实时扫描租户的贸易行为，确保其符合全球法规、伦理准则及主权安全策略，并自动执行熔断或修复
 */
export class SovereigntyGovernanceService {
  /**
   * 执行合规性扫描
   */
  static async performGovernanceCheck(tenantId: string, traceId: string): Promise<number> {
    // 1. 获取租户最近贸易活动快照
    const activities = await db('cf_orders').where({ tenant_id: tenantId }).limit(100);
    
    // 2. 调用 AGI 治理引擎进行多维度审计 (法规、伦理、政治风险)
    const auditResult = await AIService.auditSovereignCompliance(tenantId, activities);
    
    await db.transaction(async (trx) => {
      // 3. 记录治理事件
      for (const violation of auditResult.violations) {
        await trx('cf_sov_governance').insert({
          tenant_id: tenantId,
          policy_type: violation.type,
          violation_description: violation.description,
          action_taken: violation.suggestedAction,
          compliance_score: auditResult.globalScore
        });

        // 4. 自动执行治理动作 (如熔断高风险订单)
        if (violation.suggestedAction === 'FREEZE') {
          await AuditService.log({
            tenant_id: tenantId,
            action: 'SOVEREIGN_GOVERNANCE_FREEZE',
            target_type: 'TENANT_ACCOUNT',
            target_id: tenantId,
            trace_id: traceId,
            new_data: JSON.stringify({ reason: violation.description }),
            metadata: JSON.stringify({ score: auditResult.globalScore })
          });
        }
      }
    });

    return auditResult.globalScore;
  }

  /**
   * 获取租户合规性画像
   */
  static async getComplianceProfile(tenantId: string) {
    const latest = await db('cf_sov_governance')
      .where({ tenant_id: tenantId })
      .orderBy('created_at', 'desc')
      .first();
    
    const history = await db('cf_sov_governance')
      .where({ tenant_id: tenantId })
      .orderBy('created_at', 'desc')
      .limit(10);

    return { latest, history };
  }
}
