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

/**
 * [BIZ_SOV_05] 跨租户匿名声誉交换协议 (Sovereignty Reputation Exchange)
 * @description 核心逻辑：支持租户间匿名共享供应商/承运商评价，提升生态透明度而不泄露商业机密。
 * 具备功能开关治理与加权声誉分算法。
 */
export class SovereigntyReputationService {
  private static readonly TABLE_NAME = 'cf_sov_reputation_exchange';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.TABLE_NAME);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.TABLE_NAME} table...`);
      await db.schema.createTable(this.TABLE_NAME, (table) => {
        table.increments('id').primary();
        table.string('provider_tenant_id', 64).notNullable();
        table.string('target_entity_id', 64).notNullable();
        table.integer('rating').notNullable();
        table.text('encrypted_feedback');
        table.string('proof_hash', 100);
        table.integer('order_volume').defaultTo(1);
        table.timestamps(true, true);
        table.index(['target_entity_id']);
      });
    }
  }

  /**
   * 发布匿名评价
   */
  static async publishAnonymousRating(
    tenantId: string, 
    targetEntityId: string, 
    rating: number, 
    feedback: string,
    traceId: string,
    orderVolume: number = 1
  ): Promise<void> {
    // Feature Flag Check
    if (!(await FeatureGovernanceService.isEnabled('BIZ_SOV_REPUTATION_EXCHANGE', tenantId))) {
      logger.info(`[SovereignReputation] Service disabled for tenant ${tenantId}`);
      return;
    }

    // 1. 匿名化处理 (模拟对反馈内容进行脱敏)
    const anonymizedFeedback = await AIService.optimizeProduct(feedback, {}); // 使用现有方法模拟脱敏
    const proofHash = 'PROOF-' + Math.random().toString(36).substring(7).toUpperCase();

    await db.transaction(async (trx) => {
      await trx(this.TABLE_NAME).insert({
        provider_tenant_id: tenantId,
        target_entity_id: targetEntityId,
        rating,
        encrypted_feedback: anonymizedFeedback,
        proof_hash: proofHash,
        order_volume: orderVolume,
        created_at: new Date()
      });

      // 审计记录
      await AuditService.log({
        tenantId: tenantId,
        userId: 'SYSTEM_BOT',
        module: 'SOVEREIGN_REPUTATION',
        action: 'SOVEREIGN_REPUTATION_PUBLISHED',
        resourceType: 'ENTITY_REPUTATION',
        resourceId: targetEntityId,
        traceId: traceId,
        afterSnapshot: JSON.stringify({ rating, orderVolume }),
        result: 'success',
        source: 'node',
        metadata: { proofHash }
      });
    });
  }

  /**
   * 获取某实体的匿名声誉摘要 (BIZ_SOV_05)
   * @description 采用加权平均算法：订单量大的租户评价权重更高
   */
  static async getEntityReputation(entityId: string): Promise<any> {
    const ratings = await db(this.TABLE_NAME)
      .where({ target_entity_id: entityId });

    if (ratings.length === 0) return null;

    let totalWeightedScore = 0;
    let totalWeight = 0;

    ratings.forEach(r => {
      const weight = Math.log10(r.order_volume + 1) + 1;
      totalWeightedScore += r.rating * weight;
      totalWeight += weight;
    });

    const averageRating = totalWeightedScore / totalWeight;

    return {
      entityId,
      averageRating: averageRating.toFixed(2),
      totalRatings: ratings.length,
      totalOrderVolume: ratings.reduce((sum, r) => sum + r.order_volume, 0),
      confidenceScore: Math.min(1.0, ratings.length / 10) // 基础置信度
    };
  }

  /**
   * 生成详细的匿名声誉报告 (BIZ_SOV_05)
   */
  static async getReputationReport(entityId: string): Promise<any> {
    const summary = await this.getEntityReputation(entityId);
    if (!summary) return null;

    const topFeedbacks = await db(this.TABLE_NAME)
      .where({ target_entity_id: entityId })
      .orderBy('order_volume', 'desc')
      .limit(5);

    return {
      ...summary,
      topFeedbacks: topFeedbacks.map(f => ({
        rating: f.rating,
        feedback: f.encrypted_feedback,
        date: f.created_at
      }))
    };
  }
}
