#!/usr/bin/env node
// Acceptation P8 (sans navigateur) : API fichiers de l'éditeur Monaco + garde-fou conflit (mtime).
// Vrai daemon + vrai repo git tmp. Couvre : GET content (+mtime), PUT avec baseMtime correct → 200,
// PUT avec baseMtime périmé → 409 STALE_FILE, PUT sans baseMtime (overwrite) → 200, diff après
// édition cohérent, fs/list?includeFiles=1 (isFile), refus de traversal.
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 = 7552;
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-p8-'));
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));

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

  // ---- GET content : contenu + mtime ----
  const get1 = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=README.md`, 'GET', cookie)).json();
  check('GET /files/content : contenu + mtime', get1.content === '# demo\n' && typeof get1.mtime === 'number');
  const mtime0 = get1.mtime;

  // ---- PUT avec baseMtime correct → 200 + nouveau mtime ----
  const put1 = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, {
    wt: repo, path: 'README.md', content: '# demo\nedited via editor\n', baseMtime: mtime0,
  });
  const put1Body = await put1.json();
  check('PUT (baseMtime correct) → 200 + mtime', put1.status === 200 && typeof put1Body.mtime === 'number');

  // ---- PUT avec baseMtime périmé (l'ancien) → 409 STALE_FILE ----
  const putStale = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, {
    wt: repo, path: 'README.md', content: 'concurrent overwrite\n', baseMtime: mtime0,
  });
  const staleBody = await putStale.json();
  check('PUT (baseMtime périmé) → 409 STALE_FILE', putStale.status === 409 && staleBody.error?.code === 'STALE_FILE');

  // ---- PUT sans baseMtime (overwrite forcé) → 200 ----
  const putForce = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, {
    wt: repo, path: 'README.md', content: '# demo\nforced\n',
  });
  check('PUT (sans baseMtime, overwrite) → 200', putForce.status === 200);

  // ---- diff après édition ----
  const ch = await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json();
  check('GET /changes : README.md modifié', (ch.changes ?? []).some((c) => c.path === 'README.md' && c.unstaged));
  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('+forced'));

  // ---- création d'un nouveau fichier + lecture du langage ----
  const putNew = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, { wt: repo, path: 'src/app.ts', content: 'export const x = 1\n' });
  check('PUT (création src/app.ts) → 200', putNew.status === 200);
  const getNew = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=src/app.ts`, 'GET', cookie)).json();
  check('GET nouveau fichier : langage typescript', getNew.language === 'typescript');

  // ---- fs/list?includeFiles=1 : remonte les fichiers (arbre IDE) ----
  const fs = await (await j(`/api/v1/fs/list?path=${enc}&includeFiles=1`, 'GET', cookie)).json();
  const readme = (fs.entries ?? []).find((e) => e.name === 'README.md');
  check('fs/list?includeFiles=1 : README.md (isFile)', readme?.isFile === true);

  // ---- refus de traversal ----
  const trav = await j(`/api/v1/repos/${repoId}/files/content`, 'PUT', cookie, { wt: repo, path: '../escape.txt', content: 'x' });
  check('PUT traversal ../ refusé', trav.status === 400 || trav.status === 403);
} 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 P8: ALL GREEN' : `\nACCEPTANCE P8: ${failed.length} FAILURE(S)`);
  process.exit(failed.length === 0 ? 0 : 1);
}
