#!/usr/bin/env node
// Acceptation P9 (sans navigateur) : cycle git propre depuis l'UI (primitives P7). Vrai daemon +
// vrai repo git tmp + remote bare local (file://). Couvre : staging sélectif → commit ne prend QUE
// le sélectionné ; amend d'un commit NON poussé → OK (HEAD change) ; amend d'un commit POUSSÉ → 409
// ALREADY_PUSHED ; pull --ff-only fast-forward → OK ; pull en divergence → refusé proprement.
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const PORT = 7553;
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-p9-'));
const repo = join(tmp, 'repo');
const bare = join(tmp, 'bare.git');
const clone2 = join(tmp, 'clone2');
const g = (cwd, ...args) => execFileSync('git', args, { cwd, stdio: 'pipe' }).toString();
const cfg = (cwd) => {
  g(cwd, 'config', 'user.email', 'test@arboretum.dev');
  g(cwd, 'config', 'user.name', 'Test');
};

execFileSync('mkdir', ['-p', repo]);
g(repo, 'init', '-b', 'main');
cfg(repo);
writeFileSync(join(repo, 'a.txt'), 'a\n');
g(repo, 'add', '-A');
g(repo, 'commit', '-m', 'init');
execFileSync('git', ['init', '--bare', bare], { stdio: 'pipe' });
g(bare, 'symbolic-ref', 'HEAD', 'refs/heads/main'); // pour que les clones se placent sur main
g(repo, 'remote', 'add', 'origin', bare);
g(repo, 'push', '-u', 'origin', 'main');

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));

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 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);
  const changes = async () => (await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json()).changes ?? [];

  // ---- staging sélectif : modifier 2 fichiers, n'indexer que a.txt, committer staged ----
  writeFileSync(join(repo, 'a.txt'), 'a modified\n');
  writeFileSync(join(repo, 'b.txt'), 'b new\n');
  await j(`/api/v1/repos/${repoId}/worktrees/stage`, 'POST', cookie, { path: repo, files: ['a.txt'] });
  const commit1 = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'only a', mode: 'staged' });
  check('commit (staged) → 200', commit1.status === 200);
  const afterCommit = (await changes()).map((c) => c.path);
  check('commit ne prend QUE le fichier indexé (b.txt reste, a.txt committé)', !afterCommit.includes('a.txt') && afterCommit.includes('b.txt'));
  check('a.txt présent dans le dernier commit', g(repo, 'show', '--name-only', '--format=', 'HEAD').includes('a.txt'));

  // ---- amend d'un commit NON poussé → OK, le sujet de HEAD change ----
  const amendOk = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'only a (amended)', amend: true });
  check('amend (commit non poussé) → 200', amendOk.status === 200);
  check('amend modifie le sujet de HEAD', g(repo, 'log', '-1', '--format=%s').trim() === 'only a (amended)');

  // ---- push, puis amend d'un commit POUSSÉ → 409 ALREADY_PUSHED ----
  const push = await j(`/api/v1/repos/${repoId}/worktrees/push`, 'POST', cookie, { path: repo });
  check('push → 200', push.status === 200);
  const amendPushed = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'too late', amend: true });
  const amendBody = await amendPushed.json();
  check('amend (commit poussé) → 409 ALREADY_PUSHED', amendPushed.status === 409 && amendBody.error?.code === 'ALREADY_PUSHED');

  // ---- pull --ff-only : un commit distant en avance → fast-forward OK ----
  execFileSync('git', ['clone', bare, clone2], { stdio: 'pipe' });
  cfg(clone2);
  writeFileSync(join(clone2, 'c.txt'), 'c\n');
  g(clone2, 'add', '-A');
  g(clone2, 'commit', '-m', 'remote commit');
  g(clone2, 'push', 'origin', 'main');
  await j(`/api/v1/repos/${repoId}/worktrees/fetch`, 'POST', cookie, { path: repo });
  const pullFf = await j(`/api/v1/repos/${repoId}/worktrees/pull`, 'POST', cookie, { path: repo, mode: 'ff-only' });
  check('pull --ff-only (fast-forward) → 200', pullFf.status === 200);
  check('le commit distant est intégré (remote commit dans l’historique)', g(repo, 'log', '--format=%s').includes('remote commit'));

  // ---- divergence : commit local non poussé + commit distant → pull --ff-only refusé ----
  writeFileSync(join(repo, 'a.txt'), 'a local divergent\n');
  await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'local divergent', mode: 'all' });
  writeFileSync(join(clone2, 'd.txt'), 'd\n');
  g(clone2, 'add', '-A');
  g(clone2, 'commit', '-m', 'remote divergent');
  g(clone2, 'push', 'origin', 'main');
  await j(`/api/v1/repos/${repoId}/worktrees/fetch`, 'POST', cookie, { path: repo });
  const pullDiv = await j(`/api/v1/repos/${repoId}/worktrees/pull`, 'POST', cookie, { path: repo, mode: 'ff-only' });
  check('pull --ff-only en divergence → refusé (non-200)', pullDiv.status !== 200, `status=${pullDiv.status}`);
} 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 P9: ALL GREEN' : `\nACCEPTANCE P9: ${failed.length} FAILURE(S)`);
  process.exit(failed.length === 0 ? 0 : 1);
}
