#!/usr/bin/env node
import * as net from 'node:net';
import * as path from 'node:path';
import { spawn } from 'node:child_process';

const SOCKET = path.join(process.env.HOME!, '.mvp-serve', 'daemon.sock');

function ipc(method: string, params: Record<string, unknown> = {}): Promise<any> {
  return new Promise((resolve, reject) => {
    const sock = net.createConnection(SOCKET, () => {
      sock.write(JSON.stringify({ method, params }));
      sock.end();
    });
    let data = '';
    sock.on('data', (chunk) => { data += chunk.toString(); });
    sock.on('end', () => {
      try {
        const resp = JSON.parse(data);
        if (resp.error) reject(new Error(resp.error.message));
        else resolve(resp.result);
      } catch { reject(new Error('Invalid response')); }
    });
    sock.on('error', () => reject(new Error('Daemon not running. Start with: mvp-serve start')));
    setTimeout(() => reject(new Error('Timeout')), 10000);
  });
}

async function main() {
  const args = process.argv.slice(2);
  const cmd = args[0];

  if (!cmd) {
    console.log([
      'MVP Serve — share any directory as a web page',
      '',
      'Usage: mvp-serve <command>',
      '',
      '  add     <path> [--label <name>]  Share a directory',
      '  remove  <id>                    Stop sharing',
      '  list                             List all shares',
      '  url     <file>                   Get share URL for a file',
      '  auth    <user> <pass>            Set login credentials',
      '  status                           Show daemon status',
      '  start                            Start daemon in background',
      '  install                          Install auto-start (launchd)',
    ].join('\n'));
    return;
  }

  try {
    switch (cmd) {
      case 'add': {
        const dirPath = args[1];
        if (!dirPath) { console.error('Usage: mvp-serve add <path> [--label <name>]'); process.exit(1); }
        const labelIdx = args.indexOf('--label');
        const label = labelIdx !== -1 ? args[labelIdx + 1] : path.basename(dirPath);
        const result = await ipc('share.add', { path: dirPath, label });
        console.log(`✅ ${result.url}`);
        if (result.username) console.log(`🔑 ${result.username} / ${result.password || '(global)'}`);
        break;
      }
      case 'remove': {
        if (!args[1]) { console.error('Usage: mvp-serve remove <id>'); process.exit(1); }
        await ipc('share.remove', { id: args[1] });
        console.log('✅ Stopped');
        break;
      }
      case 'list': {
        const result = await ipc('share.list');
        if (!result.shares.length) { console.log('No shares. Add: mvp-serve add <path>'); break; }
        for (const s of result.shares) {
          const status = s.active ? '● active' : '○ paused';
          console.log(`  ${s.label.padEnd(20)} /s/${s.slug}/  ${status}`);
        }
        break;
      }
      case 'url': {
        if (!args[1]) { console.error('Usage: mvp-serve url <file>'); process.exit(1); }
        console.log((await ipc('share.get_url', { path: args[1] })).url);
        break;
      }
      case 'auth': {
        const [u, p] = [args[1], args[2]];
        if (!u || !p) { console.error('Usage: mvp-serve auth <user> <pass>'); process.exit(1); }
        await ipc('daemon.set_auth', { username: u, password: p });
        console.log(`✅ Auth: ${u}`);
        break;
      }
      case 'status': {
        const r = await ipc('daemon.status');
        console.log(`PID: ${r.pid}  Port: ${r.port}  Uptime: ${Math.round(r.uptime)}s  Shares: ${r.activeShares}`);
        break;
      }
      case 'start': {
        const daemonEntry = path.join(__dirname, '..', 'src', 'daemon', 'index.ts');
        const child = spawn('npx', ['tsx', daemonEntry], { detached: true, stdio: 'ignore' });
        child.unref();
        console.log('Daemon starting...');
        break;
      }
      default:
        console.error(`Unknown: ${cmd}`);
        process.exit(1);
    }
  } catch (e: any) {
    console.error(`❌ ${e.message}`);
    process.exit(1);
  }
}

main();
