// PRE Web GUI — Dashboard routes (quick actions, onboarding, dashboard, suggestions)
const { Router } = require('express');
const fs = require('fs');
const { listSessions } = require('../sessions');
const { listConnections } = require('../connections');
const telegramReceiver = require('../telegram-receiver');

const router = Router();

// ── Quick Actions ──

const quickActions = require('../quick-actions');

router.get('/quick-actions', (_req, res) => {
  res.json(quickActions.list());
});

router.post('/quick-actions', (req, res) => {
  const { label, icon, prompt } = req.body;
  if (!prompt) return res.status(400).json({ error: 'prompt is required' });
  res.json(quickActions.add({ label, icon, prompt, enabled: req.body.enabled }));
});

router.patch('/quick-actions/:id', (req, res) => {
  const result = quickActions.update(req.params.id, req.body);
  if (!result) return res.status(404).json({ error: 'not found' });
  res.json(result);
});

router.delete('/quick-actions/:id', (req, res) => {
  const ok = quickActions.remove(req.params.id);
  if (!ok) return res.status(404).json({ error: 'not found' });
  res.json({ success: true });
});

router.post('/quick-actions/reorder', (req, res) => {
  const { ids } = req.body;
  if (!Array.isArray(ids)) return res.status(400).json({ error: 'ids array required' });
  res.json(quickActions.reorder(ids));
});

router.post('/quick-actions/reset', (_req, res) => {
  res.json(quickActions.resetDefaults());
});

// ── Onboarding ──

const onboarding = require('../onboarding');

router.get('/onboarding', (req, res) => {
  const platform = req.query.platform || 'macos';
  res.json({
    state: onboarding.getState(),
    firstRun: onboarding.isFirstRun(),
    workflows: onboarding.getWorkflows(platform),
  });
});

router.post('/onboarding/workflow', (req, res) => {
  res.json(onboarding.markWorkflowRun(req.body.workflowId));
});

router.post('/onboarding/dismiss', (_req, res) => {
  res.json(onboarding.dismiss());
});

router.post('/onboarding/reset', (_req, res) => {
  res.json(onboarding.reset());
});

// ── Dashboard ──

router.get('/dashboard', async (_req, res) => {
  try {
    const { CRON_FILE } = require('../constants');

    const allSessions = listSessions();
    const recentSessions = allSessions
      .filter(s => {
        const name = (s.displayName || s.channel || '').toLowerCase();
        const id = (s.id || '').toLowerCase();
        if (name.startsWith('agent-') || id.includes(':agent-') || id.includes(':agent_')) return false;
        return true;
      })
      .slice(0, 5)
      .map(s => ({
        id: s.id,
        name: s.displayName || s.channel || 'Untitled',
        preview: (s.preview || '').slice(0, 100),
        time: s.modified,
      }));

    let calendarEvents = [];
    try {
      const { calendar } = require('../tools/calendar');
      const raw = await calendar({ action: 'today' });
      if (raw && !raw.startsWith('Error') && !raw.startsWith('No events') && !raw.includes('not available')) {
        const seen = new Set();
        calendarEvents = raw.split('\n').filter(Boolean).map(line => {
          const match = line.match(/\| (\d{4}-\d{2}-\d{2}) (\d{2}:\d{2})-(\d{2}:\d{2}) \| ([^|]+)/);
          if (!match) return null;
          const start = match[2], end = match[3], title = match[4].trim();
          if (start === '00:00' && end === '23:59') return null;
          const key = `${start}-${title}`;
          if (seen.has(key)) return null;
          seen.add(key);
          return { start, end, title };
        }).filter(Boolean).slice(0, 6);
      }
    } catch { /* calendar not available */ }

    let cronCount = 0;
    try {
      const crons = JSON.parse(fs.readFileSync(CRON_FILE, 'utf-8'));
      cronCount = crons.filter(c => c.enabled !== false).length;
    } catch {}

    let connectionCount = 0;
    try {
      connectionCount = Object.keys(listConnections()).filter(k => !k.startsWith('_')).length;
    } catch {}

    const tgStatus = telegramReceiver.getStatus();

    res.json({
      calendar: calendarEvents,
      recentSessions,
      stats: { cronJobs: cronCount, connections: connectionCount, telegram: tgStatus.active, telegramBot: tgStatus.username },
    });
  } catch (err) {
    res.json({ calendar: [], recentSessions: [], stats: { cronJobs: 0, connections: 0, telegram: false } });
  }
});

// ── Proactive Suggestions ──

router.get('/suggestions', async (_req, res) => {
  try {
    const suggestions = [];
    const hour = new Date().getHours();

    if (hour >= 5 && hour < 12) {
      suggestions.push({ icon: '☀️', text: 'Good morning — check your calendar and emails', prompt: 'Give me a morning briefing: check my calendar for today and summarize any important unread emails.' });
    } else if (hour >= 12 && hour < 17) {
      suggestions.push({ icon: '📋', text: 'Afternoon check-in — any tasks to follow up on?', prompt: 'What\'s left on my calendar today? Summarize any emails I may have missed this morning.' });
    } else if (hour >= 17 && hour < 22) {
      suggestions.push({ icon: '🌙', text: 'Evening wind-down — review today\'s progress', prompt: 'Give me a summary of what happened today: calendar events that occurred, any important emails, and what I accomplished.' });
    }

    try {
      const { calendar } = require('../tools/calendar');
      const raw = await calendar({ action: 'today' });
      if (raw && !raw.startsWith('Error') && !raw.startsWith('No events') && !raw.includes('not available')) {
        const now = new Date();
        const nowMins = now.getHours() * 60 + now.getMinutes();
        const events = raw.split('\n').filter(Boolean);
        for (const line of events) {
          const match = line.match(/\| \d{4}-\d{2}-\d{2} (\d{2}):(\d{2})-\d{2}:\d{2} \| ([^|]+)/);
          if (!match) continue;
          const evMins = parseInt(match[1]) * 60 + parseInt(match[2]);
          const title = match[3].trim();
          if (evMins > nowMins && evMins - nowMins <= 60) {
            const minsUntil = evMins - nowMins;
            suggestions.push({ icon: '📅', text: `${title} in ${minsUntil}m`, prompt: `Tell me about my upcoming meeting: "${title}". Check my email for any agenda or prep materials.` });
            break;
          }
        }
      }
    } catch {}

    // Unread email nudge (morning/afternoon only)
    if (hour >= 7 && hour < 18) {
      const conns = listConnections();
      if (conns.google_client_id || conns.microsoft_client_id) {
        suggestions.push({ icon: '✉️', text: 'Check for unread emails', prompt: 'Check my email and summarize any unread messages, highlighting anything urgent.' });
      }
    }

    // Stale memory nudge
    try {
      const path = require('path');
      const os = require('os');
      const memDir = path.join(os.homedir(), '.pre', 'memory');
      const memFiles = fs.readdirSync(memDir).filter(f => f.endsWith('.md'));
      if (memFiles.length > 20) {
        suggestions.push({ icon: '🧠', text: `You have ${memFiles.length} memories — review for staleness?`, prompt: 'List all my saved memories and flag any that seem outdated or no longer relevant.' });
      }
    } catch {}

    res.json(suggestions.slice(0, 3));
  } catch {
    res.json([]);
  }
});

module.exports = router;
