#!/usr/bin/env node
'use strict';
/*
 * chip-fetcher-lite CLI — thin wrapper over the local server API.
 *
 *   chip-fetcher-lite serve            start the server (foreground)
 *   chip-fetcher-lite add <name...>    add a component (starts a wiki check)
 *   chip-fetcher-lite list             list components + status
 *   chip-fetcher-lite jobs             show pending agent jobs (probe / send)
 *   chip-fetcher-lite app              open the viewer as a Hydrogen webview
 */
const { spawn, execFileSync } = require('child_process');
const path = require('path');

const PORT = parseInt(process.env.CFL_PORT || process.env.PORT || '7821', 10);
const BASE = `http://localhost:${PORT}`;

async function api(p, opts) {
  const r = await fetch(BASE + p, opts);
  if (!r.ok) throw new Error(`${r.status} ${await r.text()}`);
  return r.json();
}

async function main() {
  const [cmd, ...rest] = process.argv.slice(2);
  switch (cmd) {
    case 'serve': {
      const s = spawn(process.execPath, [path.join(__dirname, 'server.js')], { stdio: 'inherit', env: process.env });
      s.on('exit', c => process.exit(c || 0));
      break;
    }
    case 'add': {
      const name = rest.join(' ').trim();
      if (!name) { console.error('usage: add <name>'); process.exit(1); }
      const c = await api('/api/components', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }) });
      console.log(`added ${c.name} (${c.id}) — checking wiki…`);
      break;
    }
    case 'list': {
      const s = await api('/api/state');
      for (const c of s.components) {
        const n = ['kicad', 'altium', 'fusion'].filter(e => c.eda[e].present);
        console.log(`${c.name.padEnd(22)} ${c.wiki.status.padEnd(9)} [${n.join(',') || '—'}]  ${c.type}`);
      }
      break;
    }
    case 'jobs': {
      const s = await api('/api/jobs');
      console.log(JSON.stringify(s.jobs, null, 2));
      break;
    }
    case 'app': {
      const proxy = process.env.VSCODE_PROXY_URI;
      if (!proxy) { console.log(`open ${BASE} in a browser`); break; }
      const url = proxy.replace('{{port}}', String(PORT));
      try {
        execFileSync('adom-cli', ['hydrogen', 'webview', 'open-or-refresh', '--name', 'Chip Fetcher Lite', '--url', url], { stdio: 'inherit' });
      } catch (e) { console.log(`open this URL as a webview:\n  ${url}`); }
      break;
    }
    default:
      console.log('chip-fetcher-lite <serve|add|list|jobs|app>');
  }
}
main().catch(e => { console.error(e.message); process.exit(1); });