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

/**
 * [BIZ_SOV_13] 主权自治统一账本 (SovereignLedgerService)
 * @description 在自治生态中，通过 AGI 审计并记录所有维度的价值交换（碳信用、人才、IP、流动性资产），确立主权级的统一价值度量衡与审计链。
 */
export class SovereignLedgerService {
  private static readonly LEDGER_TABLE = 'cf_sov_ledger';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.LEDGER_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.LEDGER_TABLE} table...`);
      await db.schema.createTable(this.LEDGER_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('exchange_type', 32).notNullable(); // ASSET, CARBON, TALENT, IP
        table.string('direction', 16).notNullable(); // IN, OUT
        table.decimal('value_amount', 20, 2).notNullable(); // 价值金额
        table.string('asset_unit', 32).notNullable(); // USD, CO2e, HOURS, LICENSES
        table.string('counterparty_tenant_id', 64);
        table.string('status', 32).defaultTo('AUDITED'); // AUDITED, DISPUTED, VOID
        table.json('audit_proof'); // AGI 生成的审计证明
        table.string('trace_id', 128);
        table.timestamps(true, true);
        table.index(['tenant_id', 'exchange_type']);
      });
      logger.info(`✅ Table ${this.LEDGER_TABLE} created`);
    }
  }

  /**
   * 记录并审计价值交换
   */
  static async recordExchange(
    tenantId: string,
    exchangeData: any,
    traceId: string
  ): Promise<boolean> {
    logger.info(`[SovereignLedger] Recording ${exchangeData.type} exchange for tenant ${tenantId} | traceId: ${traceId}`);

    // 1. AGI 进行实时价值审计与防欺诈校验
    const audit = await AIService.analyzeSecurityRisk(`Audit value exchange: ${JSON.stringify(exchangeData)}`, traceId);
    
    if (audit.includes('HIGH_RISK')) {
      logger.error(`[SovereignLedger] Exchange audit failed: ${audit}`);
      return false;
    }

    // 2. 持久化记录
    await db(this.LEDGER_TABLE).insert({
      tenant_id: tenantId,
      exchange_type: exchangeData.type,
      direction: exchangeData.direction,
      value_amount: exchangeData.amount,
      asset_unit: exchangeData.unit,
      counterparty_tenant_id: exchangeData.counterparty,
      status: 'AUDITED',
      audit_proof: JSON.stringify({ proof: audit }),
      trace_id: traceId,
      created_at: new Date(),
      updated_at: new Date()
    });

    return true;
  }

  /**
   * 获取租户主权净值报表 (AGI 驱动)
   */
  static async getSovereignNetWorth(tenantId: string, traceId: string) {
    const records = await db(this.LEDGER_TABLE).where({ tenant_id: tenantId });
    
    // 调用 AGI 进行跨维度价值换算 (如将碳信用与人才时长转换为统一的主权积分)
    const prompt = `Calculate sovereign net worth for tenant ${tenantId} based on ledger: ${JSON.stringify(records)}`;
    const valuation = await AIService.generateStrategy(prompt, traceId);

    return {
      tenantId,
      recordsCount: records.length,
      sovereignValuation: valuation
    };
  }
}
