"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SwarmService = void 0;
const AIModels_1 = require("../models/AIModels");
class SwarmService {
    aiService;
    constructor(aiService) {
        this.aiService = aiService;
    }
    async swarmAnalysis(models, messages, context) {
        const modelInstances = models
            .map(id => (0, AIModels_1.getModelById)(id))
            .filter((m) => m !== undefined);
        // Get responses from all models in parallel
        const responses = await Promise.all(modelInstances.map(async (model) => {
            try {
                if (!this.aiService.hasApiKey(model.provider)) {
                    return null;
                }
                const response = await this.aiService.chat(model, messages, 'ask', context);
                return {
                    model: model.name,
                    modelId: model.id,
                    response: response.content,
                    confidence: this.calculateConfidence(response.content)
                };
            }
            catch (error) {
                console.error(`Error with model ${model.name}:`, error);
                return null;
            }
        }));
        const validResponses = responses.filter((r) => r !== null);
        // Generate consensus
        const consensus = this.generateConsensus(validResponses);
        // Voting mechanism
        const voting = await this.getVotes(modelInstances, messages, consensus, context);
        return {
            consensus,
            individualResponses: validResponses.map(r => ({
                model: r.model,
                response: r.response,
                confidence: r.confidence
            })),
            voting
        };
    }
    calculateConfidence(content) {
        // Simple heuristic: longer, more structured responses = higher confidence
        const hasCodeBlocks = (content.match(/```/g) || []).length;
        const hasStructure = content.includes('\n\n') || content.includes('1.') || content.includes('-');
        const lengthScore = Math.min(content.length / 500, 1);
        return Math.min(0.5 + (hasCodeBlocks * 0.15) + (hasStructure ? 0.2 : 0) + (lengthScore * 0.15), 1);
    }
    generateConsensus(responses) {
        if (responses.length === 0) {
            return 'No responses available from the swarm.';
        }
        if (responses.length === 1) {
            return responses[0].response;
        }
        // Find common themes and create consensus
        const allText = responses.map(r => r.response).join('\n\n---\n\n');
        // Weight by confidence
        const weightedResponses = responses
            .sort((a, b) => b.confidence - a.confidence);
        return `## 🧠 Swarm Consensus (${responses.length} AI models analyzed)

**Highest Confidence Response (${weightedResponses[0].model}):**
${weightedResponses[0].response}

${responses.length > 1 ? `\n**Additional Perspectives:**\n${responses.slice(1).map(r => `\n### ${r.model} (Confidence: ${(r.confidence * 100).toFixed(0)}%)\n${r.response}`).join('\n')}` : ''}

**Synthesis:** Based on analysis from ${responses.length} AI models, the consensus suggests the approach above.`;
    }
    async getVotes(models, messages, consensus, context) {
        const votes = [];
        for (const model of models.slice(0, 3)) { // Limit to 3 for voting
            try {
                if (!this.aiService.hasApiKey(model.provider))
                    continue;
                const votePrompt = {
                    role: 'user',
                    content: `Review this consensus solution and vote:\n\n${consensus}\n\nVote: APPROVE, REJECT, or MODIFY. Provide brief reasoning.`
                };
                const response = await this.aiService.chat(model, [...messages, votePrompt], 'ask', context);
                const vote = this.parseVote(response.content);
                votes.push({
                    model: model.name,
                    vote: vote.vote,
                    reasoning: vote.reasoning
                });
            }
            catch (error) {
                console.error(`Voting error with ${model.name}:`, error);
            }
        }
        return votes;
    }
    parseVote(content) {
        const lower = content.toLowerCase();
        let vote = 'approve';
        if (lower.includes('reject') || lower.includes('disagree') || lower.includes('wrong')) {
            vote = 'reject';
        }
        else if (lower.includes('modify') || lower.includes('improve') || lower.includes('change')) {
            vote = 'modify';
        }
        return { vote, reasoning: content.substring(0, 200) };
    }
}
exports.SwarmService = SwarmService;
//# sourceMappingURL=SwarmService.js.map