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

export interface FeatureFlag {
  featureKey: string;
  isEnabled: boolean;
  description: string;
  scope: 'GLOBAL' | 'TENANT';
  metadata?: Record<string, any>;
}

/**
 * [BIZ_GOV_06] 功能治理服务 (Feature Governance / Feature Flags)
 * @description 核心逻辑：管理系统的功能开关，支持全局开关与租户级动态控制。
 */
export class FeatureGovernanceService {
  private static readonly TABLE_NAME = 'cf_feature_flags';
  private static readonly TENANT_FLAGS_TABLE = 'cf_tenant_feature_flags';
  private static readonly AUDIT_LOG_TABLE = 'cf_feature_audit_logs';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasFlagsTable = await db.schema.hasTable(this.TABLE_NAME);
    if (!hasFlagsTable) {
      logger.info(`📦 Creating ${this.TABLE_NAME} table...`);
      await db.schema.createTable(this.TABLE_NAME, (table) => {
        table.string('feature_key', 100).primary();
        table.boolean('is_enabled').defaultTo(true);
        table.string('description', 255);
        table.string('scope', 20).defaultTo('GLOBAL');
        table.json('metadata');
        table.timestamps(true, true);
      });

      // 初始化 V24.0+ 不确定功能的开关
      await db(this.TABLE_NAME).insert([
        { feature_key: 'CORE_AI_RCA', is_enabled: true, description: 'LLM 级供应链异常根因分析', scope: 'GLOBAL' },
        { feature_key: 'CORE_SEC_ZKP', is_enabled: true, description: '基于零知识证明的资质验证', scope: 'GLOBAL' },
        { feature_key: 'BIZ_FIN_TAX_PLANNING', is_enabled: true, description: '智能税务筹划', scope: 'GLOBAL' },
        { feature_key: 'CORE_AI_SENTIMENT', is_enabled: true, description: '多模态 SKU 情感分析', scope: 'GLOBAL' },
        { feature_key: 'BIZ_FIN_CASHFLOW', is_enabled: true, description: '实时现金流预测', scope: 'GLOBAL' },
        { feature_key: 'CORE_LOG_SEMANTIC', is_enabled: true, description: '语义日志搜索', scope: 'GLOBAL' },
        { feature_key: 'CORE_EXT_MM_AI', is_enabled: true, description: '多模态商品理解 AI', scope: 'GLOBAL' },
        { feature_key: 'BIZ_TRADE_BLOCKCHAIN', is_enabled: true, description: '区块链供应链溯源', scope: 'GLOBAL' },
        { feature_key: 'CORE_SEC_STREAM_AUDIT', is_enabled: true, description: '全链路加密数据流审计', scope: 'GLOBAL' },
        { feature_key: 'BIZ_TRADE_ROUTE_OPT', is_enabled: true, description: '动态物流路由优化', scope: 'GLOBAL' },
        { feature_key: 'BIZ_FIN_INVOICING', is_enabled: true, description: '全球自动化发票系统', scope: 'GLOBAL' },
        { feature_key: 'CORE_AI_LOCALIZATION', is_enabled: true, description: '多语言翻译与文化适配引擎', scope: 'GLOBAL' },
        { feature_key: 'CORE_SEC_HOMOMORPHIC', is_enabled: true, description: '同态加密利润汇总', scope: 'GLOBAL' },
        { feature_key: 'BIZ_FIN_CREDIT_LINE', is_enabled: true, description: '租户信用额度动态管理', scope: 'GLOBAL' },
        { feature_key: 'CORE_DEV_VECTOR_SYNC_V2', is_enabled: true, description: '向量索引增量同步 V2', scope: 'GLOBAL' },
        { feature_key: 'CORE_TELE_PREDICTIVE_HEALTH', is_enabled: true, description: '预测性系统健康度看板', scope: 'GLOBAL' },
        { feature_key: 'BIZ_TRADE_AUTO_INSURANCE', is_enabled: true, description: '自动化物流保险按需采购', scope: 'GLOBAL' },
        { feature_key: 'CORE_AUTO_RL_CRAWLER', is_enabled: true, description: '基于强化学习的爬虫策略优化', scope: 'GLOBAL' },
        { feature_key: 'CORE_AI_KG_SOURCING', is_enabled: true, description: '基于知识图谱的选品关联推理', scope: 'GLOBAL' },
        { feature_key: 'BIZ_FIN_HEDGING', is_enabled: true, description: '跨租户大宗商品价格对冲', scope: 'GLOBAL' },
        { feature_key: 'CORE_SEC_CONTINUOUS_AUTH', is_enabled: true, description: '零信任节点身份连续认证', scope: 'GLOBAL' },
        { feature_key: 'BIZ_TRADE_LAST_MILE', is_enabled: true, description: '最后一公里配送成本优化', scope: 'GLOBAL' },
        { feature_key: 'CORE_AUTO_SWARM_CONSENSUS', is_enabled: true, description: '自治 Agent 群组冲突解决协议', scope: 'GLOBAL' },
        { feature_key: 'CORE_AI_IMAGE_COLLISION', is_enabled: true, description: '跨平台 SKU 图像指纹碰撞检测', scope: 'GLOBAL' },
        { feature_key: 'CORE_DEV_EDGE_WASM', is_enabled: true, description: '基于 WASM 的轻量级边缘计算算子', scope: 'GLOBAL' },
        { feature_key: 'BIZ_MKT_ARBITRAGE_AGI', is_enabled: true, description: '基于 AGI 的全球选品套利机会挖掘', scope: 'GLOBAL' },
        { feature_key: 'CORE_SEC_HARDWARE_ENCLAVE', is_enabled: true, description: '硬件隔离级别的租户敏感逻辑执行', scope: 'GLOBAL' },
        { feature_key: 'BIZ_AUTO_VISION_FACTORY', is_enabled: true, description: '供应商生产车间实时视频流异常感知', scope: 'GLOBAL' },
        { feature_key: 'CORE_AI_UNCERTAINTY', is_enabled: true, description: '全球物流时效不确定性量化', scope: 'GLOBAL' },
        { feature_key: 'CORE_SEC_DIFF_PRIVACY', is_enabled: true, description: '基于差分隐私的报表分析', scope: 'GLOBAL' },
        { feature_key: 'BIZ_FIN_POOL_SOURCING', is_enabled: true, description: '跨租户集中采购议价池', scope: 'GLOBAL' },
        { feature_key: 'CORE_AUTO_TOPO_HEALING', is_enabled: true, description: '自愈式 Pipeline 步骤拓扑重构', scope: 'GLOBAL' },
        { feature_key: 'BIZ_TRADE_CONGESTION_FAILOVER', is_enabled: true, description: '全球物流拥堵预测与自适应绕路建议', scope: 'GLOBAL' },
        { feature_key: 'CORE_DEV_DIST_LOCK_V2', is_enabled: true, description: '分布式锁优化 V2', scope: 'GLOBAL' },
        { feature_key: 'BIZ_MKT_SOCIAL_PULSE', is_enabled: true, description: '社交媒体趋势实时对齐', scope: 'GLOBAL' },
        { feature_key: 'CORE_SEC_PROOF_OF_COMPUTATION', is_enabled: true, description: '跨节点机密计算证明链', scope: 'GLOBAL' },
        { feature_key: 'CORE_AI_RESOURCE_RESERVATION', is_enabled: true, description: '租户资源预留模型', scope: 'GLOBAL' },
        { feature_key: 'CORE_DEV_TX_SENTINEL', is_enabled: true, description: '自愈式分布式事务检测器', scope: 'GLOBAL' },
        { feature_key: 'CORE_AI_RISK_PROPAGATION', is_enabled: true, description: '供应链中断风险传播分析', scope: 'GLOBAL' },
        { feature_key: 'BIZ_MKT_DYNAMIC_PRICING_V3', is_enabled: true, description: '基于个性化画像的动态调价', scope: 'GLOBAL' },
        { feature_key: 'CORE_SEC_PROMPT_GUARD', is_enabled: true, description: 'LLM 注入指令安全过滤层', scope: 'GLOBAL' },
        { feature_key: 'CORE_AI_STYLE_ALIGNMENT', is_enabled: true, description: '多模态素材风格对齐', scope: 'GLOBAL' },
        { feature_key: 'BIZ_SOV_REPUTATION_EXCHANGE', is_enabled: true, description: '跨租户匿名声誉交换', scope: 'GLOBAL' },
        { feature_key: 'BIZ_GOV_QUOTA_BREAKER', is_enabled: true, description: '租户配额超支自动限流与熔断', scope: 'GLOBAL' },
        { feature_key: 'CORE_DEV_REALTIME_METRICS', is_enabled: true, description: '毫秒级业务指标聚合引擎', scope: 'GLOBAL' },
        { feature_key: 'CORE_SEC_DID_HANDSHAKE', is_enabled: true, description: '基于 DID 的跨租户安全握手', scope: 'GLOBAL' },
        { feature_key: 'CORE_DEV_DATA_TIERING', is_enabled: true, description: 'PB 级冷热数据自动迁移', scope: 'GLOBAL' },
        { feature_key: 'BIZ_AUDIT_RED_TEAMING', is_enabled: true, description: '自动化合规红蓝对抗', scope: 'GLOBAL' },
        { feature_key: 'CORE_TELE_COST_ATTRIBUTION', is_enabled: true, description: '租户级 API 成本对齐审计', scope: 'GLOBAL' },
        { feature_key: 'UX_IAT_SWARM_3D', is_enabled: true, description: '多 Agent 决策博弈 3D 可视化', scope: 'GLOBAL' },
        { feature_key: 'CORE_TELE_TRACING_TOPO', is_enabled: true, description: '全球分布式追踪拓扑实时重构', scope: 'GLOBAL' },
        { feature_key: 'UX_IAT_LOW_CODE_LOGIC', is_enabled: true, description: '自适应业务逻辑编排可视化', scope: 'GLOBAL' },
        { feature_key: 'BIZ_AUDIT_DATA_COMPLIANCE', is_enabled: true, description: '跨区域数据流动合规性扫描', scope: 'GLOBAL' },
        { feature_key: 'CORE_TELE_AUTO_DIAGNOSTICS', is_enabled: true, description: '系统级瓶颈 AI 自动诊断', scope: 'GLOBAL' },
        { feature_key: 'BIZ_GOV_SLA_MONITORING', is_enabled: true, description: '租户 SLA 实时达成度监控', scope: 'GLOBAL' },
        { feature_key: 'CORE_AGI_VALUE_SHARING', is_enabled: true, description: '多 Agent 博弈论价值分配', scope: 'GLOBAL' },
        { feature_key: 'CORE_SEC_PRIVATE_AUDIT', is_enabled: true, description: '基于 ZKP 的隐私审计', scope: 'GLOBAL' },
        { feature_key: 'CORE_DEV_INFINITY_COMPUTE', is_enabled: true, description: '无限水平扩展 AGI 算力池', scope: 'GLOBAL' },
        { feature_key: 'BIZ_GOV_BEHAVIORAL_RISK', is_enabled: true, description: '租户行为风险动态监控', scope: 'GLOBAL' },
        { feature_key: 'CORE_AI_KNOWLEDGE_DISTILLATION', is_enabled: true, description: '跨模态 AGI 知识蒸馏', scope: 'GLOBAL' },
        { feature_key: 'CORE_AI_SEMANTIC_DRIFT', is_enabled: true, description: '跨语言语义对齐漂移自动修正', scope: 'GLOBAL' },
        { feature_key: 'BIZ_AUDIT_AGENT_TRACE', is_enabled: true, description: 'AI 代理行为轨迹审计', scope: 'GLOBAL' },
        { feature_key: 'UX_IAT_DECISION_HEATMAP', is_enabled: true, description: 'AGI 决策因子热力图', scope: 'GLOBAL' },
        { feature_key: 'BIZ_ECO_03_AUTONOMOUS_SOURCING', is_enabled: true, description: '自治供应链全球寻源与自动签约', scope: 'GLOBAL' },
        { feature_key: 'BIZ_SOV_SETTLEMENT', is_enabled: true, description: '跨平台资金主权结算', scope: 'GLOBAL' },
        { feature_key: 'BIZ_SOV_ARBITRATION', is_enabled: true, description: '去中心化贸易纠纷自动仲裁', scope: 'GLOBAL' },
        { feature_key: 'BIZ_FIN_CREDIT_POOL', is_enabled: true, description: '基于主权身份的全球授信池', scope: 'GLOBAL' },
        { feature_key: 'BIZ_TRADE_FULFILLMENT_CONSENSUS', is_enabled: true, description: '去中心化物流履约验证共识', scope: 'GLOBAL' },
        { feature_key: 'BIZ_ECO_VALUE_SHARING', is_enabled: true, description: '供应商生态价值共享博弈', scope: 'GLOBAL' },
        { feature_key: 'CORE_DEV_HOT_RELOAD_V2', is_enabled: true, description: '分布式配置热更新 V2', scope: 'GLOBAL' },
        { feature_key: 'CORE_AGI_BASE_MODE', is_enabled: false, description: 'AGI 基础模式 (开启后将跳过重型 AGI 计算，聚焦核心贸易)', scope: 'TENANT' },
        { feature_key: 'BIZ_START_ONBOARDING', is_enabled: true, description: '新手引导与阶梯任务看板', scope: 'TENANT' },
        { feature_key: 'BIZ_START_QUICK_LIST', is_enabled: true, description: '极速刊登与选品雷达', scope: 'TENANT' },
        { feature_key: 'BIZ_START_ONE_CLICK_SETUP', is_enabled: true, description: '一键店铺初始化', scope: 'TENANT' }
      ]);
    }

    const hasTenantFlagsTable = await db.schema.hasTable(this.TENANT_FLAGS_TABLE);
    if (!hasTenantFlagsTable) {
      logger.info(`📦 Creating ${this.TENANT_FLAGS_TABLE} table...`);
      await db.schema.createTable(this.TENANT_FLAGS_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('feature_key', 100).notNullable();
        table.boolean('is_enabled').notNullable();
        table.unique(['tenant_id', 'feature_key']);
        table.timestamps(true, true);
      });
    }

    const hasAuditTable = await db.schema.hasTable(this.AUDIT_LOG_TABLE);
    if (!hasAuditTable) {
      logger.info(`📦 Creating ${this.AUDIT_LOG_TABLE} table...`);
      await db.schema.createTable(this.AUDIT_LOG_TABLE, (table) => {
        table.increments('id').primary();
        table.string('feature_key', 100).notNullable();
        table.string('tenant_id', 64); // null if global
        table.boolean('old_value');
        table.boolean('new_value');
        table.string('operator_id', 64);
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }

  /**
   * 检查功能是否启用
   */
  static async isEnabled(featureKey: string, tenantId?: string): Promise<boolean> {
    try {
      // 1. 先查全局开关
      const globalFlag = await db(this.TABLE_NAME).where({ feature_key: featureKey }).first();
      if (!globalFlag) return true; // 默认开启
      if (!globalFlag.is_enabled) return false;

      // 2. 如果是租户级功能，查租户覆盖配置
      if (tenantId && globalFlag.scope === 'TENANT') {
        const tenantFlag = await db(this.TENANT_FLAGS_TABLE)
          .where({ tenant_id: tenantId, feature_key: featureKey })
          .first();
        if (tenantFlag) return !!tenantFlag.is_enabled;
      }

      return !!globalFlag.is_enabled;
    } catch (err: any) {
      logger.error(`[FeatureGov] Failed to check flag ${featureKey}: ${err.message}`);
      return true; // 故障回退：默认开启
    }
  }

  /**
   * 切换全局开关 (Admin API 调用)
   */
  static async toggleGlobalFeature(featureKey: string, isEnabled: boolean, operatorId?: string) {
    const oldVal = await db(this.TABLE_NAME).where({ feature_key: featureKey }).first();
    
    await db(this.TABLE_NAME)
      .where({ feature_key: featureKey })
      .update({ is_enabled: isEnabled, updated_at: new Date() });
    
    await db(this.AUDIT_LOG_TABLE).insert({
      feature_key: featureKey,
      old_value: oldVal ? !!oldVal.is_enabled : null,
      new_value: isEnabled,
      operator_id: operatorId,
      created_at: new Date()
    });

    logger.warn(`[FeatureGov] Feature ${featureKey} global status changed to ${isEnabled}`);
  }

  /**
   * 设置租户级覆盖配置
   */
  static async setTenantOverride(tenantId: string, featureKey: string, isEnabled: boolean, operatorId?: string) {
    const oldVal = await db(this.TENANT_FLAGS_TABLE).where({ tenant_id: tenantId, feature_key: featureKey }).first();

    await db(this.TENANT_FLAGS_TABLE)
      .insert({
        tenant_id: tenantId,
        feature_key: featureKey,
        is_enabled: isEnabled,
        updated_at: new Date()
      })
      .onConflict(['tenant_id', 'feature_key'])
      .merge();
    
    await db(this.AUDIT_LOG_TABLE).insert({
      feature_key: featureKey,
      tenant_id: tenantId,
      old_value: oldVal ? !!oldVal.is_enabled : null,
      new_value: isEnabled,
      operator_id: operatorId,
      created_at: new Date()
    });

    logger.info(`[FeatureGov] Tenant ${tenantId} override set for ${featureKey}: ${isEnabled}`);
  }

  /**
   * 注册新功能 (Dynamic Registration)
   */
  static async registerFeature(flag: FeatureFlag) {
    await db(this.TABLE_NAME)
      .insert({
        feature_key: flag.featureKey,
        is_enabled: flag.isEnabled,
        description: flag.description,
        scope: flag.scope,
        metadata: flag.metadata ? JSON.stringify(flag.metadata) : null,
        updated_at: new Date()
      })
      .onConflict('feature_key')
      .merge();
    logger.info(`[FeatureGov] Feature registered/updated: ${flag.featureKey}`);
  }

  /**
   * 获取所有功能详情及其当前状态
   */
  static async getAllFeatures(tenantId?: string): Promise<any[]> {
    const globalFlags = await db(this.TABLE_NAME).select('*');
    
    if (!tenantId) return globalFlags;

    const tenantOverrides = await db(this.TENANT_FLAGS_TABLE).where({ tenant_id: tenantId });
    const overrideMap = new Map(tenantOverrides.map(o => [o.feature_key, o.is_enabled]));

    return globalFlags.map(flag => ({
      ...flag,
      tenant_override: overrideMap.has(flag.feature_key) ? !!overrideMap.get(flag.feature_key) : null,
      effective_status: overrideMap.has(flag.feature_key) ? !!overrideMap.get(flag.feature_key) : !!flag.is_enabled
    }));
  }
}
