const express = require('express');
const axios = require('axios');
const NodeCache = require('node-cache');

const router = express.Router();
const cache = new NodeCache({ stdTTL: 600 }); // insights cached 10 min

// ── POST /api/insights/site ───────────────────────────────────
// Accepts metrics + keywords + tasks for a site, returns AI insight
router.post('/site', async (req, res, next) => {
  const { site, metrics, keywords, tasks, competitors } = req.body;
  if (!site) return res.status(400).json({ error: 'site required' });

  const cacheKey = `insight_${site}_${JSON.stringify({ metrics, keywords: keywords?.slice(0,5) })}`.slice(0, 200);
  const cached = cache.get(cacheKey);
  if (cached) return res.json(cached);

  try {
    const declining = (keywords || []).filter(k => k.movement === 'down').slice(0, 5);
    const improving = (keywords || []).filter(k => k.movement === 'up').slice(0, 5);
    const openTasks = [...(tasks?.todo || []), ...(tasks?.inProgress || [])].slice(0, 5);

    const prompt = `You are an expert SEO analyst reviewing data for ${site}.

METRICS (last 28 days vs previous 28 days):
- Clicks: ${metrics?.current?.clicks} (${metrics?.deltas?.clicks}% change)
- Impressions: ${metrics?.current?.impressions} (${metrics?.deltas?.impressions}% change)
- CTR: ${metrics?.current?.ctr}% (${metrics?.deltas?.ctr}pp change)
- Avg Position: ${metrics?.current?.position} (${metrics?.deltas?.position} spots change)

TOP DECLINING KEYWORDS:
${declining.map(k => `- "${k.keyword}" dropped from #${k.prevPosition} to #${k.position}`).join('\n') || 'None'}

TOP IMPROVING KEYWORDS:
${improving.map(k => `- "${k.keyword}" improved from #${k.prevPosition} to #${k.position}`).join('\n') || 'None'}

OPEN TASKS:
${openTasks.map(t => `- ${t.name}`).join('\n') || 'None'}

Write ONE concise insight (2-3 sentences max) that:
1. Identifies the single most important thing happening on this site right now
2. Explains why it matters
3. Gives ONE specific, actionable recommendation

Be direct and specific. No generic advice. Reference actual keyword names and numbers.`;

    const response = await axios.post(
      'https://api.anthropic.com/v1/messages',
      {
        model: 'claude-sonnet-4-20250514',
        max_tokens: 200,
        messages: [{ role: 'user', content: prompt }],
      },
      {
        headers: {
          'x-api-key': process.env.ANTHROPIC_API_KEY,
          'anthropic-version': '2023-06-01',
          'Content-Type': 'application/json',
        },
      }
    );

    const insight = response.data.content[0]?.text || 'No insight available.';
    const result = { site, insight, generatedAt: new Date().toISOString() };
    cache.set(cacheKey, result);
    res.json(result);
  } catch (err) {
    // Fallback insight if API call fails
    res.json({ site, insight: `Data loaded for ${site}. Configure ANTHROPIC_API_KEY in .env to enable AI insights.`, generatedAt: new Date().toISOString() });
  }
});

// ── POST /api/insights/keyword ────────────────────────────────
// Deep-dive recommendations for a specific keyword
router.post('/keyword', async (req, res, next) => {
  const { keyword, site, position, prevPosition, searchVolume, competitors } = req.body;
  if (!keyword) return res.status(400).json({ error: 'keyword required' });

  try {
    const prompt = `You are an SEO expert. Give me specific, actionable recommendations to improve rankings for the keyword "${keyword}" on ${site || 'the target site'}.

Current data:
- Position: #${position} (previously #${prevPosition || 'unknown'})
- Search volume: ${searchVolume || 'unknown'}/month

Provide 3-5 concrete, technical recommendations. Be specific about what to do, not generic SEO platitudes. Format as a numbered list.`;

    const response = await axios.post(
      'https://api.anthropic.com/v1/messages',
      { model: 'claude-sonnet-4-20250514', max_tokens: 500, messages: [{ role: 'user', content: prompt }] },
      { headers: { 'x-api-key': process.env.ANTHROPIC_API_KEY, 'anthropic-version': '2023-06-01', 'Content-Type': 'application/json' } }
    );

    res.json({ keyword, recommendations: response.data.content[0]?.text });
  } catch (err) {
    next(err);
  }
});

module.exports = router;
