// PRE Web GUI — System routes (debug, status, health, autostart)
const { Router } = require('express');
const http = require('http');
const os = require('os');
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const { healthCheck } = require('../ollama');
const { getProvider } = require('../connections');
const { IS_WIN, IS_MAC, IS_LINUX } = require('../platform');

const router = Router();

// ── Debug info ──

router.get('/debug', async (_req, res) => {
  const { MODEL, MODEL_CTX, OLLAMA_PORT } = require('../constants');
  let ollamaStatus = 'unknown';
  let ollamaModels = [];
  try {
    const ok = await healthCheck();
    ollamaStatus = ok ? 'healthy' : 'unreachable';
  } catch { ollamaStatus = 'error'; }
  try {
    const resp = await new Promise((resolve, reject) => {
      const req = http.request({ hostname: '127.0.0.1', port: OLLAMA_PORT, path: '/api/tags', method: 'GET', timeout: 5000 }, (r) => {
        let d = ''; r.on('data', c => { d += c; }); r.on('end', () => { try { resolve(JSON.parse(d)); } catch { resolve(null); } });
      }); req.on('error', reject); req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); }); req.end();
    });
    if (resp && resp.models) ollamaModels = resp.models.map(m => ({ name: m.name, size: m.size, modified: m.modified_at }));
  } catch {}
  res.json({
    platform: os.platform(),
    arch: os.arch(),
    totalMemGB: Math.floor(os.totalmem() / (1024 ** 3)),
    freeMemGB: Math.floor(os.freemem() / (1024 ** 3)),
    model: MODEL,
    modelCtx: MODEL_CTX,
    ollamaPort: OLLAMA_PORT,
    ollamaStatus,
    ollamaModels,
    provider: (() => { const p = getProvider(); return { type: p.type || 'ollama' }; })(),
    nodeVersion: process.version,
    uptime: Math.floor(process.uptime()),
  });
});

// ── Status ──

router.get('/status', async (_req, res) => {
  const { MODEL_CTX } = require('../constants');
  const CWD = process.env.PRE_CWD || os.homedir();
  const provider = getProvider();
  const backendUp = await healthCheck();
  res.json({
    ollama: backendUp,
    backend: backendUp,
    provider: provider.type || 'ollama',
    cwd: CWD,
    model_ctx: MODEL_CTX,
    platform: IS_WIN ? 'windows' : IS_MAC ? 'macos' : 'linux',
  });
});

// ── Health ──

router.get('/health', (_req, res) => res.json({ ok: true }));

// ── Autostart (platform-specific) ──

const PLIST_LABEL = 'com.pre.server';
const PLIST_PATH = IS_MAC ? path.join(os.homedir(), 'Library', 'LaunchAgents', `${PLIST_LABEL}.plist`) : '';
const PRE_SERVER_SH = path.join(__dirname, '..', '..', 'pre-server.sh');

// Windows: VBScript in Startup folder
const WIN_STARTUP_DIR = IS_WIN ? path.join(os.homedir(), 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup') : '';
const WIN_STARTUP_VBS = IS_WIN ? path.join(WIN_STARTUP_DIR, 'PRE-Server.vbs') : '';
const PRE_SERVER_PS1 = path.join(__dirname, '..', '..', 'pre-server.ps1');

const SYSTEMD_USER_DIR = IS_LINUX ? path.join(os.homedir(), '.config', 'systemd', 'user') : '';
const SYSTEMD_SERVICE = IS_LINUX ? path.join(SYSTEMD_USER_DIR, 'pre-server.service') : '';

router.get('/system/autostart', (_req, res) => {
  if (IS_WIN) {
    const installed = fs.existsSync(WIN_STARTUP_VBS);
    res.json({ installed, running: installed, startupPath: WIN_STARTUP_VBS });
    return;
  }
  if (IS_LINUX) {
    const installed = fs.existsSync(SYSTEMD_SERVICE);
    let running = false;
    if (installed) {
      try {
        execSync('systemctl --user is-active pre-server 2>/dev/null', { encoding: 'utf-8' });
        running = true;
      } catch { /* not active */ }
    }
    res.json({ installed, running, servicePath: SYSTEMD_SERVICE });
    return;
  }
  // macOS
  const installed = fs.existsSync(PLIST_PATH);
  let running = false;
  if (installed) {
    try {
      const out = execSync(`launchctl list ${PLIST_LABEL} 2>/dev/null`, { encoding: 'utf-8' });
      running = !out.includes('"Label"') || true;
    } catch { /* not loaded */ }
  }
  res.json({ installed, running, plistPath: PLIST_PATH });
});

router.post('/system/autostart', (req, res) => {
  const { enabled } = req.body || {};
  const webDir = path.join(__dirname, '..', '..');

  if (IS_LINUX) {
    if (enabled) {
      const nodePath = process.execPath;
      const unit = `[Unit]
Description=PRE Personal Reasoning Engine — Web GUI
After=network.target

[Service]
Type=simple
WorkingDirectory=${webDir}
ExecStart=${nodePath} ${path.join(webDir, 'server.js')}
Environment=PRE_WEB_PORT=7749
Restart=on-failure
RestartSec=5

[Install]
WantedBy=default.target
`;
      try {
        if (!fs.existsSync(SYSTEMD_USER_DIR)) fs.mkdirSync(SYSTEMD_USER_DIR, { recursive: true });
        fs.writeFileSync(SYSTEMD_SERVICE, unit);
        execSync('systemctl --user daemon-reload', { timeout: 10000 });
        execSync('systemctl --user enable pre-server', { timeout: 10000 });
        execSync('systemctl --user start pre-server', { timeout: 10000 });
        res.json({ installed: true, running: true });
      } catch (err) {
        res.status(500).json({ error: err.message });
      }
    } else {
      try {
        execSync('systemctl --user stop pre-server 2>/dev/null', { timeout: 10000 });
        execSync('systemctl --user disable pre-server 2>/dev/null', { timeout: 10000 });
      } catch { /* not running */ }
      if (fs.existsSync(SYSTEMD_SERVICE)) fs.unlinkSync(SYSTEMD_SERVICE);
      try { execSync('systemctl --user daemon-reload', { timeout: 10000 }); } catch { /* ok */ }
      res.json({ installed: false, running: false });
    }
    return;
  }

  if (IS_WIN) {
    if (enabled) {
      const winDir = webDir.replace(/\//g, '\\');
      const vbs = `Set WshShell = CreateObject("WScript.Shell")\r\n`
        + `WshShell.CurrentDirectory = "${winDir}"\r\n`
        + `WshShell.Run "powershell.exe -NoProfile -ExecutionPolicy Bypass -File ""${PRE_SERVER_PS1.replace(/\//g, '\\')}""", 0, False\r\n`;
      try {
        if (!fs.existsSync(WIN_STARTUP_DIR)) fs.mkdirSync(WIN_STARTUP_DIR, { recursive: true });
        fs.writeFileSync(WIN_STARTUP_VBS, vbs);
        res.json({ installed: true, running: true });
      } catch (err) {
        res.status(500).json({ error: err.message });
      }
    } else {
      if (fs.existsSync(WIN_STARTUP_VBS)) fs.unlinkSync(WIN_STARTUP_VBS);
      res.json({ installed: false, running: false });
    }
    return;
  }

  // macOS
  if (enabled) {
    const plist = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>${PLIST_LABEL}</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>${PRE_SERVER_SH}</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <dict>
        <key>SuccessfulExit</key>
        <false/>
    </dict>
    <key>WorkingDirectory</key>
    <string>${webDir}</string>
    <key>StandardOutPath</key>
    <string>/tmp/pre-server.log</string>
    <key>StandardErrorPath</key>
    <string>/tmp/pre-server.log</string>
    <key>EnvironmentVariables</key>
    <dict>
        <key>PATH</key>
        <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
        <key>HOME</key>
        <string>${os.homedir()}</string>
        <key>OLLAMA_FLASH_ATTENTION</key>
        <string>0</string>
        <key>OLLAMA_KEEP_ALIVE</key>
        <string>24h</string>
        <key>OLLAMA_NUM_PARALLEL</key>
        <string>1</string>
        <key>OLLAMA_MAX_LOADED_MODELS</key>
        <string>1</string>
    </dict>
</dict>
</plist>`;
    const dir = path.dirname(PLIST_PATH);
    if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
    fs.writeFileSync(PLIST_PATH, plist);
    try { execSync(`launchctl load "${PLIST_PATH}" 2>/dev/null`); } catch { /* already loaded */ }
    res.json({ installed: true, running: true });
  } else {
    if (fs.existsSync(PLIST_PATH)) fs.unlinkSync(PLIST_PATH);
    res.json({ installed: false, running: false });
  }
});

module.exports = router;
