#!/usr/bin/env node
// Thin CLI wrapper for kicad-library-manager.
//   klm serve        start the server (port 7823, KLM_PORT to override)
//   klm app          open it as a Hydrogen webview (best-effort)
//   klm probe        kick a library probe via the running server
'use strict';
const { spawn, execFile } = require('child_process');
const path = require('path');
const http = require('http');

const ROOT = __dirname;
const PORT = parseInt(process.env.KLM_PORT || '7823', 10);
const cmd = process.argv[2] || 'serve';

function post(p, body) {
  return new Promise((resolve, reject) => {
    const data = Buffer.from(JSON.stringify(body || {}));
    const req = http.request({ host: '127.0.0.1', port: PORT, path: p, method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Content-Length': data.length } },
      res => { let b = ''; res.on('data', d => b += d); res.on('end', () => resolve(b)); });
    req.on('error', reject); req.write(data); req.end();
  });
}

if (cmd === 'serve' || cmd === 'start') {
  const p = spawn(process.execPath, [path.join(ROOT, 'server.js')], { stdio: 'inherit', env: process.env });
  p.on('exit', code => process.exit(code || 0));
} else if (cmd === 'probe') {
  post('/api/probe-request', { edas: ['kicad'] }).then(r => { console.log(r); }).catch(e => { console.error(e.message); process.exit(1); });
} else if (cmd === 'app') {
  const url = `http://127.0.0.1:${PORT}/`;
  execFile('adom-cli', ['hydrogen', 'webview', 'open-or-refresh', '--name', 'KiCad Library Manager', '--url', url],
    (err, out) => { if (err) { console.error('Could not open webview:', err.message); console.log('Open manually:', url); } else console.log(out || ('Opened ' + url)); });
} else {
  console.log('usage: klm [serve|app|probe]');
  process.exit(1);
}