import db from '../config/database';
import { AuditService } from './AuditService';
import { AIService } from './AIService';
import { SovereigntyReputationService } from './SovereigntyReputationService';
import { AutonomousEcoService } from './AutonomousEcoService';
import { FeatureGovernanceService } from '../core/governance/FeatureGovernanceService';

/**
 * [BIZ_ECO_03] 自治供应链全球寻源与自动签约 (Autonomous Sourcing)
 * 负责端到端的全球寻源流程：发现 -> 声誉核验 -> 风险评估 -> 自动签约
 */
export class AutonomousSourcingService {
  private static readonly TABLE_NAME = 'cf_autonomous_sourcing';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.TABLE_NAME);
    if (!hasTable) {
      console.log(`📦 Creating ${this.TABLE_NAME} table...`);
      await db.schema.createTable(this.TABLE_NAME, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable().index();
        table.string('category', 64).notNullable();
        table.string('status', 32).notNullable();
        table.json('discovered_suppliers');
        table.string('contract_id', 64);
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.timestamp('updated_at').defaultTo(db.fn.now());
      });
      console.log(`✅ Table ${this.TABLE_NAME} created`);
    }
  }

  /**
   * 启动自治寻源流程
   */
  static async startSourcing(tenantId: string, category: string, traceId: string): Promise<void> {
    // Feature Flag Check
    if (!(await FeatureGovernanceService.isEnabled('BIZ_ECO_03_AUTONOMOUS_SOURCING', tenantId))) {
      console.warn(`[Sourcing] Sourcing skipped: Feature disabled for Tenant ${tenantId}`);
      return;
    }

    console.info(`[Sourcing] Starting autonomous sourcing for ${category} (Tenant: ${tenantId})`);

    // 1. 记录寻源任务开始
    const [sourcingId] = await db('cf_autonomous_sourcing').insert({
      tenant_id: tenantId,
      category,
      status: 'SEARCHING'
    });

    // 2. AGI 发现潜在供应商 (模拟)
    // 模拟数据：替代 AIService.scanGlobalSuppliers
    const discoveredSuppliers = [
      { id: 'supplier-1', name: 'Global Supplier Inc.' },
      { id: 'supplier-2', name: 'Quality Manufacturers Ltd.' },
      { id: 'supplier-3', name: 'Eco-friendly Products Co.' }
    ];
    
    await db('cf_autonomous_sourcing')
      .where({ id: sourcingId })
      .update({
        discovered_suppliers: JSON.stringify(discoveredSuppliers),
        status: 'EVALUATING',
        updated_at: db.fn.now()
      });

    // 3. 深度评估 (联动 BIZ_SOV_05 匿名声誉交换)
    for (const supplier of discoveredSuppliers) {
      const reputation = await SovereigntyReputationService.getEntityReputation(supplier.id);
      
      // 如果声誉分 > 4.5 且 评价数 > 10，则自动发起签约意向
      if (reputation && reputation.averageRating > 4.5 && reputation.totalReviews > 10) {
        await this.autoContractSupplier(tenantId, supplier.id, category, sourcingId, traceId);
      }
    }
  }

  /**
   * 自动签约供应商 (联动 BIZ_ECO_01)
   */
  private static async autoContractSupplier(
    tenantId: string, 
    supplierId: string, 
    category: string, 
    sourcingId: number,
    traceId: string
  ): Promise<void> {
    // 借用 AutonomousEcoService 的签约逻辑
    await AutonomousEcoService.discoverAndEvaluateSuppliers(tenantId, category, traceId);

    // 更新寻源任务状态
    await db('cf_autonomous_sourcing')
      .where({ id: sourcingId })
      .update({
        status: 'CONTRACTED',
        contract_id: `CON-${Date.now()}-${supplierId.slice(-4)}`,
        updated_at: db.fn.now()
      });

    await AuditService.log({
      tenantId: tenantId,
      userId: 'SYSTEM_BOT',
      module: 'AUTONOMOUS_SOURCING',
      action: 'AUTONOMOUS_SOURCING_COMPLETED',
      resourceType: 'SUPPLY_CHAIN',
      resourceId: supplierId,
      traceId: traceId,
      afterSnapshot: JSON.stringify({ category, supplierId }),
      result: 'success',
      source: 'node',
      metadata: { sourcingId }
    });
  }

  /**
   * 获取寻源任务历史
   */
  static async getSourcingHistory(tenantId: string) {
    return await db('cf_autonomous_sourcing')
      .where({ tenant_id: tenantId })
      .orderBy('created_at', 'desc');
  }
}
