// backend/src/routes/demo.js
// Public, rate-limited endpoint for the landing page live demo.
// No auth required — generates sample topics to show off the product.

import { Router } from 'express';
import rateLimit from 'express-rate-limit';
import { createProvider } from '../services/ai-provider.js';
import { logger } from '../utils/logger.js';

const router = Router();

// Strict rate limit: 3 demo generations per IP per 10 minutes
const demoLimiter = rateLimit({
  windowMs: 10 * 60 * 1000,
  max: 3,
  message: { error: 'demo_limit', message: 'Demo limit reached. Sign up for unlimited topics!' },
  standardHeaders: true,
});

// POST /api/demo/topics  — generate 3 sample topics for a niche
router.post('/topics', demoLimiter, async (req, res) => {
  const { niche } = req.body;

  if (!niche || typeof niche !== 'string' || niche.trim().length < 2) {
    return res.status(400).json({ error: 'Please provide a niche' });
  }
  if (niche.length > 120) {
    return res.status(400).json({ error: 'Niche too long' });
  }

  // Use the platform's cheapest model for demos to control cost
  const apiKey = process.env.ANTHROPIC_API_KEY || process.env.OPENAI_API_KEY;
  if (!apiKey) {
    // Graceful fallback to templated topics if no platform key configured
    return res.json({ topics: templateTopics(niche), source: 'template' });
  }

  try {
    const provider = process.env.ANTHROPIC_API_KEY
      ? createProvider('claude', process.env.ANTHROPIC_API_KEY, 'claude-haiku-4-5-20251001')
      : createProvider('openai', process.env.OPENAI_API_KEY, 'gpt-4o-mini');

    const system = `You generate catchy, specific YouTube video topic ideas. You respond ONLY with valid JSON, no markdown, no preamble.`;
    const prompt = `Generate exactly 3 specific, clickable YouTube video topics for the niche: "${niche.trim()}".

Respond with ONLY this JSON structure (no markdown fences):
[
  {"title": "specific clickable title", "angle": "2-3 word angle", "difficulty": "easy|medium|hard"},
  {"title": "...", "angle": "...", "difficulty": "..."},
  {"title": "...", "angle": "...", "difficulty": "..."}
]

Make titles specific and curiosity-driven, NOT generic. Bad: "How to lose weight". Good: "Why 80% of Women Over 35 Can't Lose Belly Fat".`;

    const raw = await provider.complete(system, prompt, 600);

    // Parse JSON safely
    let topics;
    try {
      const cleaned = raw.replace(/```json|```/g, '').trim();
      topics = JSON.parse(cleaned);
    } catch {
      topics = templateTopics(niche);
    }

    if (!Array.isArray(topics) || topics.length === 0) {
      topics = templateTopics(niche);
    }

    res.json({ topics: topics.slice(0, 3), source: 'ai' });
  } catch (err) {
    logger.warn('Demo generation failed, using template', err.message);
    res.json({ topics: templateTopics(niche), source: 'template' });
  }
});

function templateTopics(niche) {
  const n = niche.trim();
  const cap = n.charAt(0).toUpperCase() + n.slice(1);
  const all = [
    { title: `Why 80% of People Fail at ${cap} (And What Actually Works)`, angle: 'Contrarian', difficulty: 'medium' },
    { title: `The 5-Minute ${cap} Routine That Changed Everything`, angle: 'Tactical', difficulty: 'easy' },
    { title: `I Tried Every ${cap} Hack for 30 Days. Here's What Worked.`, angle: 'Experiment', difficulty: 'medium' },
    { title: `${cap}: The Honest Beginner's Guide (No BS)`, angle: 'Educational', difficulty: 'hard' },
    { title: `The Hidden Truth About ${cap} Nobody Tells You`, angle: 'Curiosity', difficulty: 'medium' },
  ];
  return all.sort(() => Math.random() - 0.5).slice(0, 3);
}

export default router;
