const crypto = require('crypto');

function registerOperationsRoutes(app, { db, ai, memory, workflowHistory, metricsAutomation }) {
  app.get('/api/metrics/:division_id', (req, res) => {
    res.json({
      config: db.prepare('SELECT * FROM metrics_config WHERE division_id = ?').all(req.params.division_id),
      data: db.prepare('SELECT * FROM metrics_data WHERE division_id = ? ORDER BY date ASC').all(req.params.division_id)
    });
  });

  app.post('/api/metrics', (req, res) => {
    const { division_id: divisionId, metric_key: metricKey, value, date } = req.body;
    const existing = db.prepare('SELECT id FROM metrics_data WHERE division_id = ? AND metric_key = ? AND date = ?').get(divisionId, metricKey, date);
    if (existing) {
      db.prepare('UPDATE metrics_data SET value = ?, is_mock = 0 WHERE id = ?').run(value, existing.id);
    } else {
      db.prepare('INSERT INTO metrics_data (division_id, metric_key, value, date, is_mock) VALUES (?, ?, ?, ?, 0)').run(divisionId, metricKey, value, date);
    }
    res.json({ success: true });
  });

  app.post('/api/metrics/collect', (req, res) => {
    const result = metricsAutomation.collectForDate(req.body?.date || null);
    res.json({ success: true, ...result });
  });

  app.post('/api/metrics/interpret', async (req, res) => {
    const { division_id: divisionId } = req.body;
    const division = db.prepare('SELECT * FROM divisions WHERE id = ?').get(divisionId);
    const settings = db.prepare('SELECT * FROM settings WHERE id = 1').get();
    const config = db.prepare('SELECT * FROM metrics_config WHERE division_id = ?').all(divisionId);
    const data = db.prepare('SELECT * FROM metrics_data WHERE division_id = ? AND is_mock = 0 ORDER BY date DESC LIMIT 30').all(divisionId);
    if (data.length === 0) {
      return res.json({ insight: 'No real data yet. Start logging daily metrics to get AI interpretation.' });
    }

    const dataStr = config.map((metric) => {
      const values = data.filter((entry) => entry.metric_key === metric.metric_key).map((entry) => `${entry.date}:${entry.value}`).slice(0, 7).join(', ');
      return `${metric.metric_label}: ${values || 'no data'}`;
    }).join('\n');

    try {
      const prompt = `Analyze these metrics for "${division.name}" and give a 2-3 sentence tactical insight. What's trending? What action is required?\n${dataStr}\nReturn ONLY plain text, no markdown.`;
      const insight = await ai.callAI(prompt, settings, `You are a data analyst for this business. ${ai.buildBusinessContext()} ${ai.buildLanguageInstruction(settings, { plainText: true })}`);
      res.json({ insight });
    } catch (error) {
      res.json({ insight: 'AI interpretation unavailable. Check AI settings.' });
    }
  });

  app.get('/api/battle_plans/:division_id', (req, res) => {
    res.json({ plans: db.prepare('SELECT * FROM battle_plans WHERE division_id = ? ORDER BY id DESC').all(req.params.division_id) });
  });

  app.post('/api/battle_plans', (req, res) => {
    const { division_id: divisionId, period, title } = req.body;
    const createdAt = new Date().toISOString();
    const result = db.prepare('INSERT INTO battle_plans (division_id, period, title, created_at) VALUES (?, ?, ?, ?)').run(divisionId, period, title, createdAt);

    if (period === 'daily') {
      const cardTitle = `🔥 Daily Execution (${createdAt.split('T')[0]})`;
      let executionCard = db.prepare('SELECT id FROM items WHERE division_id = ? AND title = ?').get(divisionId, cardTitle);
      if (!executionCard) {
        executionCard = {
          id: workflowHistory.createItem({
            divisionId,
            title: cardTitle,
            magicLink: crypto.randomUUID(),
            workDate: createdAt.slice(0, 10)
          })
        };
      }
      workflowHistory.addTodo({
        itemId: executionCard.id,
        divisionId,
        text: `[BP] ${title.substring(0, 100)}`,
        workDate: createdAt.slice(0, 10)
      });
    }

    res.json({ id: result.lastInsertRowid });
  });

  app.post('/api/battle_plans/ai-generate', async (req, res) => {
    const { division_id: divisionId, target_period: targetPeriod } = req.body;
    const division = db.prepare('SELECT * FROM divisions WHERE id = ?').get(divisionId);
    const settings = db.prepare('SELECT * FROM settings WHERE id = 1').get();
    const existing = db.prepare('SELECT period, title FROM battle_plans WHERE division_id = ?').all(divisionId);

    let context = 'Existing Strategy:\n';
    existing.forEach((plan) => {
      const shouldInclude =
        (targetPeriod === 'monthly' && plan.period === 'yearly') ||
        (targetPeriod === 'weekly' && ['yearly', 'monthly'].includes(plan.period)) ||
        (targetPeriod === 'daily' && ['yearly', 'monthly', 'weekly'].includes(plan.period));
      if (shouldInclude) context += `- [${plan.period.toUpperCase()}] ${plan.title}\n`;
    });

    try {
      const aiText = await ai.callAI(
        `Generate exactly 3 highly tactical '${targetPeriod}' goals. ${context} Return ONLY a raw JSON array of 3 strings (max 15 words each).`,
        settings,
        `Expert AI Director for "${division.name}". VFP: "${division.vfp}". ${ai.buildBusinessContext()} ${ai.buildLanguageInstruction(settings, { json: true })}`
      );
      const rawPlans = ai.parseJsonResponse(aiText);
      const now = new Date().toISOString();

      // Normalise objects → strings (AI sometimes returns [{goal:"..."}] instead of ["..."])
      const normalisePlan = (p) => {
        if (typeof p === 'string') return p.trim();
        if (typeof p === 'object' && p !== null) {
          const val = p.goal || p.title || p.text || p.content || p.plan || p.objective || Object.values(p)[0];
          return String(val || '').trim();
        }
        return String(p).trim();
      };

      const plans = (Array.isArray(rawPlans) ? rawPlans : ['Analyze metrics', 'Refine strategy', 'Execute today'])
        .map(normalisePlan)
        .filter((p) => p.length > 3)
        .slice(0, 3);

      const insertPlan = db.prepare('INSERT INTO battle_plans (division_id, period, title, created_at) VALUES (?, ?, ?, ?)');
      plans.forEach((plan) => insertPlan.run(divisionId, targetPeriod, plan.substring(0, 200), now));

      if (targetPeriod === 'daily') {
        const cardTitle = `🔥 Daily Execution (${now.split('T')[0]})`;
        let executionCard = db.prepare('SELECT id FROM items WHERE division_id = ? AND title = ?').get(divisionId, cardTitle);
        if (!executionCard) {
          executionCard = {
            id: workflowHistory.createItem({
              divisionId,
              title: cardTitle,
              magicLink: crypto.randomUUID(),
              workDate: now.slice(0, 10)
            })
          };
        }
        plans.forEach((plan) => workflowHistory.addTodo({
          itemId: executionCard.id,
          divisionId,
          text: `[BP] ${plan.substring(0, 100)}`,
          workDate: now.slice(0, 10)
        }));
      }

      res.json({ success: true, plans });
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  });

  app.put('/api/battle_plans/:id/toggle', (req, res) => {
    const done = req.body.done ? 1 : 0;
    db.prepare('UPDATE battle_plans SET done = ? WHERE id = ?').run(done, req.params.id);
    if (done === 1) {
      const battlePlan = db.prepare('SELECT title, division_id FROM battle_plans WHERE id = ?').get(req.params.id);
      memory.logMemory(battlePlan.division_id, 'battle_plan_achieved', `Achieved goal: '${battlePlan.title}'`);
    }
    res.json({ success: true });
  });

  app.delete('/api/battle_plans/:id', (req, res) => {
    db.prepare('DELETE FROM battle_plans WHERE id = ?').run(req.params.id);
    res.json({ success: true });
  });

  app.get('/api/trainings/:division_id', (req, res) => {
    res.json({ trainings: db.prepare('SELECT * FROM trainings WHERE division_id = ?').all(req.params.division_id) });
  });

  app.post('/api/trainings', (req, res) => {
    const result = db.prepare('INSERT INTO trainings (division_id, title, content, read_time, icon) VALUES (?, ?, ?, ?, ?)').run(
      req.body.division_id,
      req.body.title,
      req.body.content,
      req.body.read_time,
      req.body.icon
    );
    res.json({ id: result.lastInsertRowid });
  });

  app.delete('/api/trainings/:id', (req, res) => {
    db.prepare('DELETE FROM trainings WHERE id = ?').run(req.params.id);
    res.json({ success: true });
  });
}

module.exports = { registerOperationsRoutes };
