#!/usr/bin/env node
// Acceptation P3 (sans navigateur, sans quota Claude) : worktrees multi-repo + dashboard.
// Vrai daemon + vrai repo git tmp. Couvre : enregistrement repo, création worktree avec hook
// post-create, broadcast WS worktree_update, corrélation worktree↔session (bash), suppression.
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname, basename } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const WebSocket = require('ws');

const PORT = 7543;
const ORIGIN = `http://127.0.0.1:${PORT}`;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
const results = [];
const check = (name, ok, detail = '') => {
  results.push({ name, ok, detail });
  console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`);
};

const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p3-'));
const repo = join(tmp, 'demo-repo');
const wtPath = join(tmp, 'demo-repo-wt-feat');
execFileSync('mkdir', ['-p', repo]);
const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' });
git('init', '-b', 'main');
git('config', 'user.email', 'test@arboretum.dev');
git('config', 'user.name', 'Test');
execFileSync('bash', ['-lc', 'echo "# demo" > README.md'], { cwd: repo });
git('add', '-A');
git('commit', '-m', 'init');

const srv = spawn(
  'node',
  [join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
  { env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
);
let srvOut = '';
srv.stdout.on('data', (d) => (srvOut += d));
srv.stderr.on('data', (d) => (srvOut += d));

function wsClient(cookie) {
  const ws = new WebSocket(`ws://127.0.0.1:${PORT}/ws`, { headers: { Origin: ORIGIN, Cookie: cookie } });
  const state = { msgs: [] };
  ws.on('message', (data, isBinary) => {
    if (!isBinary) state.msgs.push(JSON.parse(String(data)));
  });
  const waitMsg = async (pred, timeout = 8000) => {
    const t0 = Date.now();
    while (Date.now() - t0 < timeout) {
      const m = state.msgs.find(pred);
      if (m) return m;
      await sleep(50);
    }
    return null;
  };
  return { ws, state, waitMsg, send: (m) => ws.send(JSON.stringify(m)) };
}

const j = (path, method, cookie, body) =>
  fetch(`${ORIGIN}${path}`, {
    method,
    headers: { Origin: ORIGIN, Cookie: cookie, ...(body ? { 'Content-Type': 'application/json' } : {}) },
    ...(body ? { body: JSON.stringify(body) } : {}),
  });

try {
  await sleep(1500);
  const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0];
  check('boot + token bootstrap', !!token);

  const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', Origin: ORIGIN },
    body: JSON.stringify({ token }),
  });
  const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? '';
  check('login → cookie', login.status === 200);

  const c = wsClient(cookie);
  await new Promise((res, rej) => (c.ws.on('open', res), c.ws.on('error', rej)));
  c.send({ type: 'hello', protocol: 1 });
  await c.waitMsg((m) => m.type === 'hello_ok');
  c.send({ type: 'sub', topics: ['sessions', 'worktrees'] });

  // Enregistrement du repo (avec un hook post-create).
  const addRepo = await j('/api/v1/repos', 'POST', cookie, {
    path: repo,
    postCreateHooks: [{ id: 'h1', label: 'touch', run: 'touch hook-ok.txt', enabled: true }],
  });
  const repoSummary = (await addRepo.json()).repo;
  check('POST /repos → 201 (repo valide)', addRepo.status === 201 && repoSummary?.valid === true);

  const wlist0 = await (await j('/api/v1/worktrees', 'GET', cookie)).json();
  check('GET /worktrees → main worktree présent', wlist0.worktrees.some((w) => w.isMain && w.branch === 'main'));

  // Création d'un worktree + hook + session bash.
  const created = await j(`/api/v1/repos/${repoSummary.id}/worktrees`, 'POST', cookie, {
    branch: 'feat',
    newBranch: true,
    runHooks: true,
    startSession: 'bash',
  });
  const createdBody = await created.json();
  check('POST worktree → 201', created.status === 201 && createdBody.worktree?.branch === 'feat');
  check('hook post-create exécuté', createdBody.hookResults?.[0]?.exitCode === 0 && existsSync(join(wtPath, 'hook-ok.txt')));
  check('startSession bash → session managée', createdBody.session?.command === 'bash');

  const pushed = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.branch === 'feat');
  check('broadcast WS worktree_update', !!pushed);

  // Corrélation worktree ↔ session par cwd.
  await sleep(300);
  const wlist1 = await (await j('/api/v1/worktrees', 'GET', cookie)).json();
  const feat = wlist1.worktrees.find((w) => w.branch === 'feat');
  check('corrélation worktree ↔ session (cwd)', feat?.sessions?.some((s) => s.command === 'bash' && s.live));

  // Suppression forcée (une session vit dans le worktree).
  const refused = await j(`/api/v1/repos/${repoSummary.id}/worktrees?path=${encodeURIComponent(wtPath)}&force=false`, 'DELETE', cookie);
  check('delete sans force (session live) → 409', refused.status === 409);
  const del = await j(`/api/v1/repos/${repoSummary.id}/worktrees?path=${encodeURIComponent(wtPath)}&force=true`, 'DELETE', cookie);
  check('delete force → 200', del.status === 200);
  const removed = await c.waitMsg((m) => m.type === 'worktree_removed', 8000);
  check('broadcast WS worktree_removed', !!removed);

  c.ws.close();
} catch (err) {
  check('exception', false, String(err));
} finally {
  srv.kill('SIGTERM');
  await sleep(1500);
  check('arrêt propre du daemon (SIGTERM)', srv.exitCode === 0 || srv.signalCode === null || srv.exitCode === null);
  rmSync(tmp, { recursive: true, force: true });
  const failed = results.filter((r) => !r.ok);
  console.log(failed.length === 0 ? '\nACCEPTANCE P3: ALL GREEN' : `\nACCEPTANCE P3: ${failed.length} FAILURE(S)`);
  process.exit(failed.length === 0 ? 0 : 1);
}
