import type { APIRoute } from 'astro';
import { validatePromptTest } from '@/lib/data/dataValidator';

/**
 * Prompt Testing Sandbox
 * Test prompts before burning $$$ on batch jobs
 */

function validateGodToken(request: Request): boolean {
    const token = request.headers.get('X-God-Token') ||
        request.headers.get('Authorization')?.replace('Bearer ', '') ||
        new URL(request.url).searchParams.get('token');

    const godToken = process.env.GOD_MODE_TOKEN || import.meta.env.GOD_MODE_TOKEN;
    if (!godToken) return true;
    return token === godToken;
}

/**
 * Estimate cost based on tokens
 */
function estimateCost(model: string, inputTokens: number, outputTokens: number): number {
    const pricing: Record<string, { input: number; output: number }> = {
        'gpt-4': { input: 0.03 / 1000, output: 0.06 / 1000 },
        'gpt-4-turbo': { input: 0.01 / 1000, output: 0.03 / 1000 },
        'gpt-3.5-turbo': { input: 0.0005 / 1000, output: 0.0015 / 1000 },
        'claude-3-opus': { input: 0.015 / 1000, output: 0.075 / 1000 }
    };

    const prices = pricing[model] || pricing['gpt-4'];
    return (inputTokens * prices.input) + (outputTokens * prices.output);
}

/**
 * Rough token estimation (4 chars ≈ 1 token)
 */
function estimateTokens(text: string): number {
    return Math.ceil(text.length / 4);
}

export const POST: APIRoute = async ({ request }) => {
    if (!validateGodToken(request)) {
        return new Response(JSON.stringify({ error: 'Unauthorized' }), {
            status: 401,
            headers: { 'Content-Type': 'application/json' }
        });
    }

    try {
        const testData = validatePromptTest(await request.json());

        // Replace variables in prompt
        let finalPrompt = testData.prompt;
        for (const [key, value] of Object.entries(testData.variables)) {
            finalPrompt = finalPrompt.replace(new RegExp(`\\{${key}\\}`, 'g'), value);
        }

        const inputTokens = estimateTokens(finalPrompt);

        // Simulate LLM call (in production, would call OpenAI/Anthropic API)
        const mockResponse = {
            content: `[MOCK RESPONSE]\n\nPrompt received: ${finalPrompt.substring(0, 100)}...\n\nThis is a sandbox test. To enable real LLM calls, configure OPENAI_API_KEY or ANTHROPIC_API_KEY in environment variables.`,
            tokens_used: {
                input: inputTokens,
                output: estimateTokens("Mock response placeholder"),
                total: inputTokens + 50
            }
        };

        const estimatedCost = estimateCost(
            testData.model,
            mockResponse.tokens_used.input,
            mockResponse.tokens_used.output
        );

        // Calculate batch cost if user runs 10k jobs
        const batchCosts = {
            '100': estimatedCost * 100,
            '1000': estimatedCost * 1000,
            '10000': estimatedCost * 10000,
            '100000': estimatedCost * 100000
        };

        return new Response(JSON.stringify({
            test: {
                model: testData.model,
                temperature: testData.temperature,
                max_tokens: testData.max_tokens
            },
            prompt: {
                original: testData.prompt,
                final: finalPrompt,
                variables_replaced: Object.keys(testData.variables).length
            },
            response: mockResponse.content,
            tokens: mockResponse.tokens_used,
            cost: {
                this_request: `$${estimatedCost.toFixed(6)}`,
                batch_estimates: {
                    '100_jobs': `$${batchCosts['100'].toFixed(2)}`,
                    '  1000_jobs': `$${batchCosts['1000'].toFixed(2)}`,
                    '10000_jobs': `$${batchCosts['10000'].toFixed(2)}`,
                    '100000_jobs': `$${batchCosts['100000'].toFixed(2)}`
                },
                warning: batchCosts['10000'] > 1000 ? '⚠️ 10k batch would cost > $1000!' : null
            },
            timestamp: new Date().toISOString()
        }), {
            status: 200,
            headers: { 'Content-Type': 'application/json' }
        });

    } catch (error: any) {
        return new Response(JSON.stringify({
            error: 'Prompt test failed',
            details: error.message
        }), {
            status: 500,
            headers: { 'Content-Type': 'application/json' }
        });
    }
};

export const GET: APIRoute = async ({ request }) => {
    if (!validateGodToken(request)) {
        return new Response(JSON.stringify({ error: 'Unauthorized' }), {
            status: 401,
            headers: { 'Content-Type': 'application/json' }
        });
    }

    return new Response(JSON.stringify({
        endpoint: 'POST /api/intelligence/prompts/test',
        description: 'Test prompts and estimate costs before batch execution',
        usage: {
            example: {
                prompt: 'Write a blog post about {topic} in {city}, {state}',
                variables: {
                    topic: 'local restaurants',
                    city: 'Austin',
                    state: 'TX'
                },
                model: 'gpt-4',
                max_tokens: 1000,
                temperature: 0.7
            }
        }
    }, null, 2), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
    });
};
