"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EvolutionService = void 0;
class EvolutionService {
    aiService;
    constructor(aiService) {
        this.aiService = aiService;
    }
    async evolveCode(model, originalCode, objective, generations = 3) {
        const evolutionHistory = [];
        let currentCode = originalCode;
        let generation = 1;
        while (generation <= generations) {
            const messages = [
                {
                    role: 'system',
                    content: `You are a code evolution engine. Your goal is to evolve code through generations, improving it based on fitness criteria.`
                },
                {
                    role: 'user',
                    content: `Evolve this code (Generation ${generation}/${generations}):

Objective: ${objective}

Current Code:
\`\`\`
${currentCode}
\`\`\`

Previous Generations: ${evolutionHistory.length > 0 ? evolutionHistory.map(g => `Gen ${g.generation}: Fitness ${g.fitness}`).join(', ') : 'None'}

Provide:
1. Evolved code
2. Fitness score (0-100)
3. Improvements made
4. Mutations applied`
                }
            ];
            const response = await this.aiService.chat(model, messages, 'agent', '');
            const parsed = this.parseEvolutionResponse(response.content, generation);
            evolutionHistory.push(parsed);
            currentCode = parsed.code;
            generation++;
        }
        return evolutionHistory;
    }
    parseEvolutionResponse(content, generation) {
        // Extract code
        const codeMatch = content.match(/```[\s\S]*?```/);
        const code = codeMatch ? codeMatch[0].replace(/```\w*\n?/g, '').replace(/```/g, '').trim() : '';
        // Extract fitness
        const fitnessMatch = content.match(/fitness[:\s]+(\d+)/i);
        const fitness = fitnessMatch ? parseInt(fitnessMatch[1]) : 50;
        // Extract improvements
        const improvements = [];
        const improvementMatches = content.match(/improvement[s]?[:\s]+([^\n]+)/gi);
        if (improvementMatches) {
            improvements.push(...improvementMatches.map(m => m.replace(/improvement[s]?:?\s*/i, '')));
        }
        // Extract mutations
        const mutations = [];
        const mutationMatches = content.match(/mutation[s]?[:\s]+([^\n]+)/gi);
        if (mutationMatches) {
            mutations.push(...mutationMatches.map(m => m.replace(/mutation[s]?:?\s*/i, '')));
        }
        return {
            generation,
            code: code || content,
            fitness,
            improvements: improvements.length > 0 ? improvements : ['Code evolved'],
            mutations: mutations.length > 0 ? mutations : ['Natural selection applied']
        };
    }
}
exports.EvolutionService = EvolutionService;
//# sourceMappingURL=EvolutionService.js.map