import { logger } from '../../utils/logger';
import { FeatureGovernanceService } from '../governance/FeatureGovernanceService';
import { RedisService } from '../../utils/RedisService';

export interface AgentProposal {
  agentId: string;
  taskId: string;
  proposedAction: string;
  confidence: number;
  timestamp: Date;
}

/**
 * [CORE_AUTO_07] 自治 Agent 群组冲突解决协议 (Swarm Consensus)
 * @description 核心逻辑：当多个 AI Agent 对同一任务提出不同决策时，通过共识协议（基于权重与信心度）达成最终一致。
 */
export class SwarmConsensusService {
  private static readonly PROPOSAL_PREFIX = 'swarm:proposals:';

  /**
   * 提交提案并尝试达成共识
   */
  static async submitProposal(proposal: AgentProposal, tenantId?: string): Promise<{
    consensusReached: boolean;
    finalAction?: string;
    voters: string[];
  }> {
    // Feature Flag Check
    if (!(await FeatureGovernanceService.isEnabled('CORE_AUTO_SWARM_CONSENSUS', tenantId))) {
      return { consensusReached: true, finalAction: proposal.proposedAction, voters: [proposal.agentId] };
    }

    const key = `${this.PROPOSAL_PREFIX}${proposal.taskId}`;
    
    // 1. 存储提案
    const existingRaw = await RedisService.get(key);
    const proposals: AgentProposal[] = existingRaw ? JSON.parse(existingRaw) : [];
    proposals.push(proposal);
    await RedisService.set(key, JSON.stringify(proposals), 300); // 5分钟有效

    // 2. 检查提案数量 (模拟：达到3个提案触发决策)
    if (proposals.length >= 3) {
      logger.info(`[Swarm] Consensus triggered for task ${proposal.taskId} with ${proposals.length} proposals.`);
      
      // 3. 加权投票算法 (Weighted Voting)
      const actionMap: Record<string, number> = {};
      proposals.forEach(p => {
        actionMap[p.proposedAction] = (actionMap[p.proposedAction] || 0) + p.confidence;
      });

      let winner = '';
      let maxScore = -1;
      Object.entries(actionMap).forEach(([action, score]) => {
        if (score > maxScore) {
          maxScore = score;
          winner = action;
        }
      });

      await RedisService.del(key); // 清理
      return {
        consensusReached: true,
        finalAction: winner,
        voters: proposals.map(p => p.agentId)
      };
    }

    return { consensusReached: false, voters: proposals.map(p => p.agentId) };
  }
}
