#!/usr/bin/env node
// Acceptation P7 (sans navigateur, sans quota Claude) : moteur git « IDE » + API fichiers + watcher
// FS temps réel. Vrai daemon + vrai repo git tmp + vrai client WS. Couvre : GET /changes & /diff,
// staging sélectif + commit(staged), API fichiers content GET/PUT (Monaco) + refus de traversal,
// abonnement ciblé watch → worktree_changes à l'édition, checkout externe → worktree_update, unwatch.
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync, appendFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname } 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 = 7547;
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-p7-'));
const repo = join(tmp, 'demo-repo');
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');
writeFileSync(join(repo, 'README.md'), '# demo\n');
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: ['worktrees'] });

  const addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo });
  const repoId = (await addRepo.json()).repo.id;
  check('POST /repos → 201', addRepo.status === 201 && !!repoId);
  const enc = encodeURIComponent(repo);

  // ---- GET /changes : un fichier modifié + un untracked ----
  appendFileSync(join(repo, 'README.md'), 'edited line\n');
  writeFileSync(join(repo, 'untracked.txt'), 'new\n');
  const ch = await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json();
  const byPath = Object.fromEntries((ch.changes ?? []).map((c2) => [c2.path, c2]));
  check('GET /changes : README.md modifié non indexé', byPath['README.md']?.unstaged === true && byPath['README.md']?.staged === false);
  check('GET /changes : untracked.txt détecté', byPath['untracked.txt']?.untracked === true);

  // ---- GET /diff ----
  const diff = await (await j(`/api/v1/repos/${repoId}/worktrees/diff?path=${enc}&file=README.md`, 'GET', cookie)).json();
  check('GET /diff : contient la ligne ajoutée', typeof diff.diff === 'string' && diff.diff.includes('+edited line'));

  // ---- staging sélectif + commit(staged) ----
  const stage = await j(`/api/v1/repos/${repoId}/worktrees/stage`, 'POST', cookie, { path: repo, files: ['README.md'] });
  const staged = await stage.json();
  check('POST /stage → README.md staged', staged.worktree?.git?.stagedCount >= 1);
  const commit = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'commit staged only', mode: 'staged' });
  check('POST /commit (mode=staged) → 200', commit.status === 200);
  const ch2 = await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json();
  const paths2 = (ch2.changes ?? []).map((c2) => c2.path);
  check('après commit staged : README committé, untracked restant', !paths2.includes('README.md') && paths2.includes('untracked.txt'));

  // ---- API fichiers (Monaco) : GET content + PUT + refus traversal ----
  const get1 = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=untracked.txt`, 'GET', cookie)).json();
  check('GET /files/content : contenu lu + langage', get1.content === 'new\n');
  const put = await j(`/api/v1/repos/${repoId}/files/content`, 'PUT', cookie, { wt: repo, path: 'src/app.ts', content: 'export const x = 1\n' });
  check('PUT /files/content (création) → 200', put.status === 200);
  const get2 = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=src/app.ts`, 'GET', cookie)).json();
  check('GET après PUT : contenu écrit + langage typescript', get2.content === 'export const x = 1\n' && get2.language === 'typescript');
  const trav = await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=${encodeURIComponent('../escape.txt')}`, 'GET', cookie);
  check('GET /files/content : traversal ../ refusé', trav.status === 400 || trav.status === 403);

  // ---- temps réel : watch → worktree_changes à l'édition ----
  c.send({ type: 'watch', repoId, path: repo });
  await sleep(900); // laisse chokidar finir son scan initial
  const t0 = Date.now();
  writeFileSync(join(repo, 'live.txt'), 'live edit\n');
  const changesMsg = await c.waitMsg((m) => m.type === 'worktree_changes' && m.path === repo, 6000);
  check('watch → worktree_changes ciblé reçu', !!changesMsg, changesMsg ? `${Date.now() - t0}ms` : 'timeout');
  const updMsg = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.path === repo, 3000);
  check('édition → worktree_update diffusé', !!updMsg);

  // ---- checkout externe (CLI) → worktree_update avec nouvelle branche ----
  c.state.msgs.length = 0; // reset pour ne capter que les nouveaux events
  git('branch', 'feature');
  git('checkout', 'feature');
  const branchMsg = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.isMain && m.worktree?.branch === 'feature', 6000);
  check('checkout externe → branche principale mise à jour en temps réel', !!branchMsg);

  // ---- unwatch : plus de worktree_changes ----
  c.send({ type: 'unwatch', repoId, path: repo });
  await sleep(300);
  c.state.msgs.length = 0;
  writeFileSync(join(repo, 'after-unwatch.txt'), 'x\n');
  const afterUnwatch = await c.waitMsg((m) => m.type === 'worktree_changes', 1500);
  check('unwatch → plus de worktree_changes', !afterUnwatch);

  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 P7: ALL GREEN' : `\nACCEPTANCE P7: ${failed.length} FAILURE(S)`);
  process.exit(failed.length === 0 ? 0 : 1);
}
