import path from 'node:path';
import { mkdir, writeFile, readFile } from 'node:fs/promises';
import { readBody, sendJSON } from '../utils/http.js';
import { getMcpSettings, writeMcpSettings } from '../services/mcp.js';
import { getUsageSummary, syncUsageToAdo } from '../services/usage.js';
import { startChromeDirectTest } from '../server/chrome-cdp.js';

export async function handle(req, res, url, ctx) {
  const { cwd } = ctx;

  // GET /api/gchat-config
  if (req.method === 'GET' && url.pathname === '/api/gchat-config') {
    try {
      const data = await readFile(path.join(cwd, '.sdd', 'gchat-config.json'), 'utf8');
      sendJSON(res, JSON.parse(data));
    } catch { sendJSON(res, {}); }
    return true;
  }

  // POST /api/gchat-config
  if (req.method === 'POST' && url.pathname === '/api/gchat-config') {
    try {
      const config = JSON.parse(await readBody(req));
      await mkdir(path.join(cwd, '.sdd'), { recursive: true });
      await writeFile(path.join(cwd, '.sdd', 'gchat-config.json'), JSON.stringify(config, null, 2), 'utf8');
      const giPath = path.join(cwd, '.gitignore');
      const giEntry = '.sdd/gchat-config.json';
      if (config.shared) {
        // Remove from .gitignore so the file is committed with the project
        try {
          const gi = await readFile(giPath, 'utf8');
          const cleaned = gi.split('\n').filter(l => l.trim() !== giEntry).join('\n');
          await writeFile(giPath, cleaned, 'utf8');
        } catch {}
      } else {
        // Keep out of git (default — protects the token)
        try {
          const gi = await readFile(giPath, 'utf8');
          if (!gi.includes(giEntry)) await writeFile(giPath, gi.trimEnd() + '\n' + giEntry + '\n', 'utf8');
        } catch { await writeFile(giPath, giEntry + '\n', 'utf8'); }
      }
      sendJSON(res, { ok: true });
    } catch(e) { sendJSON(res, { error: e.message }, 500); }
    return true;
  }

  // GET /api/ado-config
  if (req.method === 'GET' && url.pathname === '/api/ado-config') {
    try {
      const data = await readFile(path.join(cwd, '.sdd', 'ado-config.json'), 'utf8');
      sendJSON(res, JSON.parse(data));
    } catch { sendJSON(res, {}); }
    return true;
  }

  // POST /api/ado-config
  if (req.method === 'POST' && url.pathname === '/api/ado-config') {
    try {
      const config = JSON.parse(await readBody(req));
      await mkdir(path.join(cwd, '.sdd'), { recursive: true });
      await writeFile(path.join(cwd, '.sdd', 'ado-config.json'), JSON.stringify(config, null, 2), 'utf8');
      // Auto-add to .gitignore
      const giPath = path.join(cwd, '.gitignore');
      const giEntry = '.sdd/ado-config.json';
      try {
        const gi = await readFile(giPath, 'utf8');
        if (!gi.includes(giEntry)) await writeFile(giPath, gi.trimEnd() + '\n' + giEntry + '\n', 'utf8');
      } catch { await writeFile(giPath, giEntry + '\n', 'utf8'); }
      sendJSON(res, { ok: true });
    } catch(e) { sendJSON(res, { error: e.message }, 500); }
    return true;
  }

  // GET /api/usage/summary
  if (req.method === 'GET' && url.pathname === '/api/usage/summary') {
    try {
      const records = await getUsageSummary(cwd);
      sendJSON(res, { records });
    } catch (e) { sendJSON(res, { records: [], error: e.message }); }
    return true;
  }

  // POST /api/usage/sync — sync local JSONL to ADO git repo
  if (req.method === 'POST' && url.pathname === '/api/usage/sync') {
    try {
      const { orgUrl, project, pat, repo } = JSON.parse(await readBody(req));
      const result = await syncUsageToAdo(cwd, orgUrl, project, pat, repo);
      sendJSON(res, result);
    } catch (e) { sendJSON(res, { ok: false, error: e.message }, 500); }
    return true;
  }

  // POST /api/mcp/sanity-test
  if (req.method === 'POST' && url.pathname === '/api/mcp/sanity-test') {
    const jobId = startChromeDirectTest();
    sendJSON(res, { jobId });
    return true;
  }

  // GET /api/mcp/status
  if (req.method === 'GET' && url.pathname === '/api/mcp/status') {
    const s = await getMcpSettings(process.cwd());
    const configured = !!(s.mcpServers && s.mcpServers['chrome-devtools']);
    sendJSON(res, { configured });
    return true;
  }

  // POST /api/mcp/setup
  if (req.method === 'POST' && url.pathname === '/api/mcp/setup') {
    try {
      await writeMcpSettings(process.cwd());
      sendJSON(res, { ok: true });
    } catch (e) {
      sendJSON(res, { error: e.message }, 500);
    }
    return true;
  }

  return false;
}
