// PRE Web GUI — Live data routes (auto-refreshing artifact data feeds)
const { Router } = require('express');
const os = require('os');
const calendarTool = require('../tools/calendar');
const mailTool = require('../tools/mail');
const remindersTool = require('../tools/reminders');
const { listSessions } = require('../sessions');

const router = Router();

// ── Parsers ──

function parseCalendarText(text) {
  if (!text || typeof text !== 'string') return [];
  return text.split('\n').filter(Boolean).map(line => {
    const parts = line.split(' | ');
    const timeStr = parts[1] || '';
    const title = parts[2] || line;
    const calendar = (parts[3] || '').replace(/[[\]]/g, '');

    const m = timeStr.match(/^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})-(\d{2}:\d{2})$/);
    if (m) {
      return {
        title,
        date: m[1],
        start: `${m[1]}T${m[2]}:00`,
        end: `${m[1]}T${m[3]}:00`,
        start_time: m[2],
        end_time: m[3],
        calendar,
      };
    }
    return { title, date: timeStr, start: timeStr, end: '', start_time: '', end_time: '', calendar };
  });
}

function parseMailText(text) {
  if (!text || typeof text !== 'string') return [];
  return text.split('\n').filter(Boolean).map(line => {
    const unread = line.startsWith('[UNREAD]');
    const clean = line.replace(/^\[UNREAD\]\s*/, '');
    const parts = clean.split(' | ');
    return {
      unread,
      date: parts[1] || '',
      from: (parts[2] || '').replace(/^From:\s*/, ''),
      subject: (parts[3] || '').replace(/^Subject:\s*/, ''),
    };
  });
}

function parseRemindersText(text) {
  if (!text || typeof text !== 'string') return [];
  return text.split(/\n(?=ID:)/).filter(Boolean).map(block => {
    const firstLine = block.split('\n')[0];
    const parts = firstLine.split(' | ');
    const obj = { title: parts[1] || block };
    for (let i = 2; i < parts.length; i++) {
      const p = parts[i];
      if (p.startsWith('Due:')) obj.due = p.replace('Due: ', '');
      else if (p.startsWith('Priority:')) obj.priority = p.replace('Priority: ', '');
      else if (p.startsWith('[')) obj.list = p.replace(/[[\]]/g, '');
    }
    return obj;
  });
}

// ── Routes ──

router.get('/live/calendar', async (_req, res) => {
  try {
    const result = await calendarTool.calendar({ action: 'today' });
    res.json({ data: parseCalendarText(result), timestamp: new Date().toISOString() });
  } catch (err) {
    res.json({ data: [], error: err.message, timestamp: new Date().toISOString() });
  }
});

router.get('/live/calendar/week', async (_req, res) => {
  try {
    const result = await calendarTool.calendar({ action: 'week' });
    res.json({ data: parseCalendarText(result), timestamp: new Date().toISOString() });
  } catch (err) {
    res.json({ data: [], error: err.message, timestamp: new Date().toISOString() });
  }
});

router.get('/live/mail', async (req, res) => {
  try {
    const count = parseInt(req.query.count) || 10;
    const result = await mailTool.mail({ action: 'list_recent', count });
    res.json({ data: parseMailText(result), timestamp: new Date().toISOString() });
  } catch (err) {
    res.json({ data: [], error: err.message, timestamp: new Date().toISOString() });
  }
});

router.get('/live/reminders', async (_req, res) => {
  try {
    const result = await remindersTool.reminders({ action: 'list' });
    res.json({ data: parseRemindersText(result), timestamp: new Date().toISOString() });
  } catch (err) {
    res.json({ data: [], error: err.message, timestamp: new Date().toISOString() });
  }
});

router.get('/live/system', async (_req, res) => {
  try {
    const plat = require('../platform');
    const cpuInfo = plat.getCpuInfo();
    const memInfo = plat.getMemoryInfo();
    const battery = plat.getBatteryInfo();

    res.json({
      data: {
        hostname: os.hostname(),
        os: `${os.type()} ${os.release()} (${os.arch()})`,
        cpu: cpuInfo.name || '',
        cpu_usage: Math.round(plat.getCpuUsage() * 10) / 10,
        memory: memInfo.totalGB,
        memory_usage: memInfo.usagePct,
        disk_usage: plat.getDiskUsage(),
        uptime: `${(os.uptime() / 3600).toFixed(1)} hours`,
        battery_percent: battery.percent,
        battery_state: battery.state,
      },
      timestamp: new Date().toISOString(),
    });
  } catch (err) {
    res.json({ data: {}, error: err.message, timestamp: new Date().toISOString() });
  }
});

router.get('/live/sessions', async (_req, res) => {
  try {
    const sessions = listSessions();
    const recent = sessions.slice(0, 10).map(s => ({
      id: s.id, name: s.displayName || s.preview || s.channel,
      modified: s.modified, turns: s.turnCount,
    }));
    res.json({ data: recent, timestamp: new Date().toISOString() });
  } catch (err) {
    res.json({ data: [], error: err.message, timestamp: new Date().toISOString() });
  }
});

module.exports = router;
