import express from 'express';
import { analyzeContent } from '../lib/analyzer.js';
import { generateAIAgentScript, suggestImprovements } from '../lib/geminiAgent.js';
import { GoogleGenerativeAI } from '@google/generative-ai';
import OpenAI from 'openai';

function getDefaultModel() {
  // Keep in sync with lib/geminiAgent.js defaults
  return process.env.GEMINI_MODEL || 'gemini-2.0-flash';
}

function getDefaultOpenAIModel() {
  // Must be a chat model supported by the v1/chat/completions endpoint.
  // Default to gpt-5-mini if no explicit OPENAI_MODEL is set.
  return process.env.OPENAI_MODEL || 'gpt-5-mini';
}

const router = express.Router();

/**
 * POST /api/analyze
 * Analyze content and recommend integration mode
 */
router.post('/analyze', express.json(), async (req, res) => {
  try {
    const { htmlContent, jsContent = '' } = req.body;

    if (!htmlContent) {
      return res.status(400).json({ error: 'htmlContent is required' });
    }

    const analysis = await analyzeContent(htmlContent, jsContent);

    res.json({
      recommendedMode: analysis.recommendedMode,
      confidence: analysis.confidence,
      detectedFeatures: analysis.detectedFeatures,
      reasons: analysis.reasons,
      modeScores: analysis.modeScores
    });

  } catch (error) {
    console.error('Analysis error:', error);
    res.status(500).json({ error: error.message });
  }
});

/**
 * POST /api/generate-script
 * Generate xAPI injection script using Gemini AI
 */
router.post('/generate-script', express.json(), async (req, res) => {
  try {
    const { analysis } = req.body;

    if (!analysis) {
      return res.status(400).json({ error: 'analysis data is required' });
    }

    if (!process.env.GOOGLE_API_KEY) {
      return res.status(503).json({ 
        error: 'AI Agent not configured',
        message: 'GOOGLE_API_KEY environment variable not set'
      });
    }

    const result = await generateAIAgentScript(analysis);

    res.json({
      script: result.script,
      explanation: result.explanation,
      mode: 'agent',
      error: result.error || null
    });

  } catch (error) {
    console.error('Script generation error:', error);
    res.status(500).json({ error: error.message });
  }
});

/**
 * POST /api/suggestions
 * Get AI suggestions for content improvement
 */
router.post('/suggestions', express.json(), async (req, res) => {
  try {
    const { htmlContent, jsContent = '' } = req.body;

    if (!htmlContent) {
      return res.status(400).json({ error: 'htmlContent is required' });
    }

    if (!process.env.GOOGLE_API_KEY) {
      return res.json({ suggestions: [], message: 'AI not configured' });
    }

    const result = await suggestImprovements(htmlContent, jsContent);

    res.json(result);

  } catch (error) {
    console.error('Suggestions error:', error);
    res.status(500).json({ 
      suggestions: [],
      error: error.message 
    });
  }
});

/**
 * GET /api/status
 * Check API status and available features
 */
router.get('/status', (req, res) => {
  res.json({
    status: 'ok',
    version: '1.0.0',
    features: {
      aiAgent: !!process.env.GOOGLE_API_KEY,
      openaiAgent: !!process.env.OPENAI_API_KEY,
      timelineMode: true,
      quizMode: true,
      minimalMode: true
    },
    ai: {
      geminiModel: getDefaultModel(),
      openaiModel: getDefaultOpenAIModel()
    },
    environment: process.env.NODE_ENV || 'development',
    timestamp: new Date().toISOString()
  });
});

/**
 * GET /api/openai-models
 * For this app we only expose two curated options:
 * - cheapest: gpt-4o-mini
 * - latest: gpt-4o
 */
router.get('/openai-models', async (req, res) => {
  try {
    // Curated list (requested by user)
    return res.json({
      ok: true,
      configured: !!process.env.OPENAI_API_KEY,
      models: [
        // Only expose chat-capable models that work with
        // client.chat.completions.create.
        { id: 'gpt-5-mini',  label: 'Latest: GPT-5 mini',  tier: 'latest' },
        { id: 'gpt-4o',      label: 'Advanced: GPT-4o',    tier: 'advanced' },
        { id: 'gpt-4o-mini', label: 'Cheapest: GPT-4o mini', tier: 'cheap' }
      ]
    });
  } catch (error) {
    return res.status(500).json({
      ok: false,
      message: error?.message || String(error)
    });
  }
});

/**
 * GET /api/openai-test
 * Minimal connectivity test to OpenAI.
 */
router.get('/openai-test', async (req, res) => {
  try {
    if (!process.env.OPENAI_API_KEY) {
      return res.status(503).json({
        ok: false,
        error: 'AI not configured',
        message: 'OPENAI_API_KEY environment variable not set'
      });
    }

    const model = (req.query.model && String(req.query.model)) || getDefaultOpenAIModel();
    const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

    const startedAt = new Date().toISOString();
    const t0 = Date.now();
    const params = {
      model,
      messages: [{ role: 'user', content: 'Return exactly the text: OK' }]
    };

    // Some newer models (e.g. gpt-5-mini) only support the default
    // temperature. Avoid setting temperature explicitly for those
    // models to prevent 400 "Unsupported value" errors.
    if (model !== 'gpt-5-mini') {
      params.temperature = 0;
    }

    const result = await client.chat.completions.create(params);
    const durationMs = Date.now() - t0;
    const text = result?.choices?.[0]?.message?.content || '';

    return res.json({
      ok: true,
      model,
      startedAt,
      durationMs,
      responsePreview: text.substring(0, 200)
    });
  } catch (error) {
    return res.status(500).json({
      ok: false,
      model: (req.query.model && String(req.query.model)) || getDefaultOpenAIModel(),
      status: error?.status,
      message: error?.message || String(error)
    });
  }
});

/**
 * GET /api/ai-models
 * Lists available models for the configured key via the REST ListModels endpoint.
 */
router.get('/ai-models', async (req, res) => {
  try {
    if (!process.env.GOOGLE_API_KEY) {
      return res.status(503).json({
        ok: false,
        error: 'AI not configured',
        message: 'GOOGLE_API_KEY environment variable not set'
      });
    }

    const url = `https://generativelanguage.googleapis.com/v1beta/models?key=${encodeURIComponent(process.env.GOOGLE_API_KEY)}`;
    const r = await fetch(url, { method: 'GET' });
    const json = await r.json();

    if (!r.ok) {
      return res.status(r.status).json({
        ok: false,
        status: r.status,
        statusText: r.statusText,
        error: json
      });
    }

    // Return a simplified list
    const models = Array.isArray(json.models) ? json.models.map(m => ({
      name: m.name,
      displayName: m.displayName,
      description: m.description,
      supportedGenerationMethods: m.supportedGenerationMethods
    })) : [];

    return res.json({ ok: true, models });
  } catch (error) {
    return res.status(500).json({
      ok: false,
      message: error?.message || String(error)
    });
  }
});

/**
 * GET /api/ai-test
 * Minimal connectivity test to Gemini.
 * Returns ok + latency + a short snippet response, or a detailed error.
 */
router.get('/ai-test', async (req, res) => {
  try {
    if (!process.env.GOOGLE_API_KEY) {
      return res.status(503).json({
        ok: false,
        error: 'AI not configured',
        message: 'GOOGLE_API_KEY environment variable not set'
      });
    }

    const model = (req.query.model && String(req.query.model)) || getDefaultModel();
    const client = new GoogleGenerativeAI(process.env.GOOGLE_API_KEY);
    const genModel = client.getGenerativeModel({ model });

    const startedAt = new Date().toISOString();
    const t0 = Date.now();
    const result = await genModel.generateContent('Return exactly the text: OK');
    const durationMs = Date.now() - t0;
    const text = result?.response?.text?.() || '';

    return res.json({
      ok: true,
      model,
      startedAt,
      durationMs,
      responsePreview: text.substring(0, 200)
    });
  } catch (error) {
    return res.status(500).json({
      ok: false,
      model: (req.query.model && String(req.query.model)) || getDefaultModel(),
      status: error?.status,
      message: error?.message || String(error)
    });
  }
});

export default router;
