"use strict";
/**
 * BIG ORANGE 🍊 - Core Comparison Logic
 * Compares AI responses with different .faf context levels
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.compareContexts = compareContexts;
const sdk_1 = __importDefault(require("@anthropic-ai/sdk"));
const crypto_1 = require("crypto");
const faf_generator_1 = require("./faf-generator");
const faf_compiler_1 = require("../compiler/faf-compiler");
const fs_1 = require("fs");
const os_1 = require("os");
const path_1 = require("path");
/**
 * Compare AI responses at two different .faf scores
 * Calls Claude API twice in parallel with different context levels
 */
async function compareContexts(request) {
    console.log(`\n🍊 Comparing ${request.leftScore}% vs ${request.rightScore}%`);
    console.log(`Prompt: "${request.prompt}"\n`);
    // 1. Generate .faf instances at specified scores
    const [leftFaf, rightFaf] = await Promise.all([
        (0, faf_generator_1.generateFafInstance)(request.leftScore, request.projectPath),
        (0, faf_generator_1.generateFafInstance)(request.rightScore, request.projectPath)
    ]);
    console.log(`Generated .faf instances:`);
    console.log(`  Left: ${request.leftScore}% (${leftFaf.content.length} chars)`);
    console.log(`  Right: ${request.rightScore}% (${rightFaf.content.length} chars)\n`);
    // 2. Call Claude API twice (parallel for speed)
    const anthropic = new sdk_1.default({
        apiKey: process.env.ANTHROPIC_API_KEY
    });
    console.log('Calling Claude API...');
    const [leftResponse, rightResponse] = await Promise.all([
        callClaudeWithContext(anthropic, request.prompt, leftFaf.content, request.leftScore),
        callClaudeWithContext(anthropic, request.prompt, rightFaf.content, request.rightScore)
    ]);
    console.log('✓ Both responses received\n');
    // 3. Calculate delta metrics
    const delta = calculateDelta(leftResponse, rightResponse);
    const results = {
        sessionId: (0, crypto_1.randomUUID)(),
        timestamp: new Date(),
        leftWindow: leftResponse,
        rightWindow: rightResponse,
        delta
    };
    return results;
}
/**
 * Call Claude API with specific .faf context
 * Uses FafCompiler for real scoring, no fake metrics
 */
async function callClaudeWithContext(client, prompt, fafContent, score) {
    const startTime = Date.now();
    // Build system prompt based on .faf score
    const systemPrompt = score > 0
        ? `You are a developer with this project context:\n\n${fafContent}\n\nUse this context to inform your response.`
        : 'You are a developer with no project context. Ask clarifying questions as needed.';
    try {
        // Call Claude API
        const response = await client.messages.create({
            model: 'claude-sonnet-4-20250514',
            max_tokens: 4000,
            system: systemPrompt,
            messages: [{
                    role: 'user',
                    content: prompt
                }]
        });
        const timeToComplete = (Date.now() - startTime) / 1000;
        const aiResponse = response.content[0].type === 'text'
            ? response.content[0].text
            : '';
        // Get real FAF score using FafCompiler
        const { emoji, metadata } = await scoreFafContent(fafContent, score);
        return {
            fafScore: score,
            aiResponse,
            timeToComplete,
            emoji,
            fafMetadata: metadata
        };
    }
    catch (error) {
        console.error(`Error calling Claude (score ${score}%):`, error);
        throw error;
    }
}
/**
 * Score .faf content using FafCompiler
 * Returns championship emoji and metadata
 */
async function scoreFafContent(fafContent, expectedScore) {
    // Write .faf to temp file
    const tempDir = (0, path_1.join)((0, os_1.tmpdir)(), 'big-orange-scoring');
    (0, fs_1.mkdirSync)(tempDir, { recursive: true });
    const tempFafPath = (0, path_1.join)(tempDir, `temp-${Date.now()}.faf`);
    try {
        (0, fs_1.writeFileSync)(tempFafPath, fafContent);
        // Use FafCompiler to score
        const compiler = new faf_compiler_1.FafCompiler();
        const result = await compiler.compile(tempFafPath);
        // Get championship emoji based on score
        const emoji = getChampionshipEmoji(result.score);
        return {
            emoji,
            metadata: {
                filled: result.filled,
                total: result.total,
                checksum: result.checksum
            }
        };
    }
    catch (error) {
        console.error('Error scoring .faf:', error);
        // Fallback to expected score
        return {
            emoji: getChampionshipEmoji(expectedScore)
        };
    }
}
/**
 * Get championship emoji based on score
 * Uses FAF CLI's standard scoring tiers
 */
function getChampionshipEmoji(score) {
    if (score >= 85)
        return '🏆'; // Trophy (championship)
    if (score >= 70)
        return '🥇'; // Gold medal
    if (score >= 55)
        return '🥈'; // Silver medal
    if (score >= 40)
        return '🥉'; // Bronze medal
    if (score >= 35)
        return '🟢'; // Green (good)
    if (score >= 20)
        return '🟡'; // Yellow (warning)
    if (score >= 10)
        return '🔴'; // Red (poor)
    return '🤍'; // White (empty)
}
/**
 * Calculate delta metrics between two responses
 * Simple comparison: time saved and score improvement
 */
function calculateDelta(left, right) {
    const timeSaved = left.timeToComplete - right.timeToComplete;
    const scoreImprovement = right.fafScore - left.fafScore;
    // Generate verdict
    let verdict = '';
    if (scoreImprovement > 0) {
        if (timeSaved > 0) {
            verdict = `.faf-${right.fafScore}% completed ${timeSaved.toFixed(1)}s faster with ${scoreImprovement}% better context`;
        }
        else {
            verdict = `.faf-${right.fafScore}% had ${scoreImprovement}% better context`;
        }
    }
    else {
        verdict = 'Context levels comparison complete';
    }
    return {
        timeSaved,
        scoreImprovement,
        verdict
    };
}
//# sourceMappingURL=compare.js.map