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

/**
 * [BIZ_ECO_09] 基础节点管理服务 (NodeGovernanceV2Service)
 * @description 管理节点（工厂、仓库、货代）的基本状态和可用性。
 */
export class NodeGovernanceV2Service {
  private static readonly NODE_GOV_TABLE = 'cf_sov_node_governance';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.NODE_GOV_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.NODE_GOV_TABLE} table...`);
      await db.schema.createTable(this.NODE_GOV_TABLE, (table) => {
        table.increments('id').primary();
        table.string('node_id', 64).notNullable();
        table.string('node_type', 32).notNullable(); // FACTORY, WAREHOUSE, CARRIER
        table.decimal('performance_score', 5, 2); // 0-100
        table.string('governance_status', 32).defaultTo('HEALTHY'); // HEALTHY, QUARANTINED, EJECTED
        table.text('audit_reason'); // 状态变更原因
        table.json('compliance_history'); // { date, event, risk_level }
        table.string('trace_id', 128);
        table.timestamps(true, true);
        table.index(['node_id', 'governance_status']);
      });
      logger.info(`✅ Table ${this.NODE_GOV_TABLE} created`);
    }
  }

  /**
   * 节点审计
   */
  static async auditNode(nodeId: string, performanceData: any, traceId: string): Promise<string> {
    logger.info(`[NodeGovernanceV2] Auditing node ${nodeId} | traceId: ${traceId}`);

    // 基于性能数据进行状态判断
    let status = 'HEALTHY';
    let auditReason = 'Node is healthy';
    
    // 简单的规则判断
    if (performanceData.score < 60) {
      status = 'EJECTED';
      auditReason = 'Low performance score';
    } else if (performanceData.score < 80) {
      status = 'QUARANTINED';
      auditReason = 'Below average performance';
    }

    // 更新治理状态
    await db(this.NODE_GOV_TABLE)
      .insert({
        node_id: nodeId,
        node_type: performanceData.type,
        performance_score: performanceData.score || 100,
        governance_status: status,
        audit_reason: auditReason,
        trace_id: traceId,
        created_at: new Date(),
        updated_at: new Date()
      })
      .onConflict('node_id')
      .merge();

    if (status !== 'HEALTHY') {
      logger.warn(`[NodeGovernanceV2] Node ${nodeId} status changed to ${status}! Reason: ${auditReason}`);
      // 联动调度系统
      // TODO: 调用相关服务移除该节点
    }

    return status;
  }

  /**
   * 检查节点是否可用
   */
  static async isNodeAvailable(nodeId: string): Promise<boolean> {
    const record = await db(this.NODE_GOV_TABLE).where({ node_id: nodeId }).first();
    return !record || record.governance_status === 'HEALTHY';
  }
}
