const path = require('path');

function registerPortalAndMemoryRoutes(app, { rootDir, db, ai, memory }) {
  app.get('/api/client/portal/:magic_link', async (req, res) => {
    const item = db.prepare('SELECT * FROM items WHERE magic_link = ?').get(req.params.magic_link);
    if (!item) return res.status(404).json({ error: 'Portal link invalid or expired.' });

    const division = db.prepare('SELECT name, subtitle, color_var FROM divisions WHERE id = ?').get(item.division_id);
    const settings = db.prepare('SELECT * FROM settings WHERE id = 1').get();
    const todos = db.prepare('SELECT * FROM todos WHERE item_id = ?').all(item.id);
    const completed = todos.filter((todo) => todo.done).length;
    const total = todos.length;

    let weeklyReport = null;
    try {
      const history = db.prepare("SELECT content, timestamp FROM memory_logs WHERE content LIKE ? ORDER BY timestamp DESC LIMIT 10").all(`%'${item.title}'%`);
      if (history.length > 0) {
        const historyContext = history.map((entry) => `- ${entry.content} (${new Date(entry.timestamp).toLocaleDateString()})`).join('\n');
        const prompt = `Write a 3-sentence professional project update for client "${item.title}". Current stage: ${division.name}. Agency activity this week:\n${historyContext}\nWrite in first person as the agency. Professional and reassuring tone. Plain text only.`;
        weeklyReport = await ai.callAI(prompt, settings, `You are a professional business operations manager. ${ai.buildBusinessContext()} ${ai.buildLanguageInstruction(settings, { plainText: true })}`);
      }
    } catch (error) {}

    const recentActivity = db.prepare("SELECT content, timestamp FROM memory_logs WHERE content LIKE ? ORDER BY timestamp DESC LIMIT 8").all(`%'${item.title}'%`);
    res.json({
      client_name: item.title,
      current_stage: division.name,
      stage_desc: division.subtitle,
      stage_color: division.color_var,
      tasks_done: completed,
      tasks_total: total,
      weekly_report: weeklyReport,
      recent_updates: recentActivity
    });
  });

  app.get('/portal', (req, res) => {
    res.sendFile(path.join(rootDir, 'public', 'client.html'));
  });

  app.get('/api/memory', (req, res) => {
    const logs = db.prepare('SELECT id, division_id, type, content, timestamp, CASE WHEN embedding IS NOT NULL THEN 1 ELSE 0 END as embedded FROM memory_logs ORDER BY id DESC LIMIT 100').all();
    res.json({ logs, stats: memory.getMemoryStats() });
  });

  app.delete('/api/memory/:id', (req, res) => {
    const existing = db.prepare('SELECT id FROM memory_logs WHERE id = ?').get(req.params.id);
    if (!existing) return res.status(404).json({ error: 'memory log not found' });
    db.prepare('DELETE FROM memory_logs WHERE id = ?').run(req.params.id);
    res.json({ success: true });
  });

  app.post('/api/memory/search', async (req, res) => {
    const { query, division_id: divisionId, top_k: topK = 8 } = req.body;
    if (!query) return res.status(400).json({ error: 'query required' });
    const settings = db.prepare('SELECT * FROM settings WHERE id = 1').get();
    res.json({ results: await memory.searchMemory(query, settings, divisionId, topK) });
  });

  app.post('/api/memory/backfill', async (req, res) => {
    const { done, total } = await memory.backfillEmbeddings();
    if (total === 0) {
      return res.json({ message: 'All logs already embedded.', count: 0 });
    }
    res.json({ message: `Backfilled ${done}/${total} memory logs.`, count: done });
  });
}

module.exports = { registerPortalAndMemoryRoutes };
