import fs from 'node:fs';
import path from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { publicSnapshot, compareOriginalState, hash } from './retained-host-state.mjs';
import { inspectHostInstallation } from '../src/core/desktop/app-installation.mjs';

// Retained-state 1.25.1 to 1.25.2 local upgrade. One installer operation only;
// preserve every first failure and never restart the formal Provider or read keys.
const attempt = process.argv[3] ?? 'formal', url = 'http://127.0.0.1:4318', mode = process.argv[2];
assert.match(attempt, /^formal(-attempt-[0-9]+)?$/);
const root = path.resolve('.qa/reliability-1.25.2', attempt);
assert.ok(['before', 'upgrade', 'final'].includes(mode));
const { execFileSync } = await import('node:child_process');
const sourceCommit = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8', windowsHide: true }).trim();
assert.equal(execFileSync('git', ['status', '--porcelain'], { encoding: 'utf8', windowsHide: true }).trim(), '', 'Release driver needs a clean reviewed tree.');
fs.mkdirSync(root, { recursive: true });
const read = file => JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
const save = (name, value) => fs.writeFileSync(path.join(root, name), JSON.stringify(value, null, 2) + '\n', { flag: 'wx' });
assert.equal(fs.existsSync(path.join(root, mode + '.json')), false, 'Preserve the original attempt; no automatic replay.');
const baseline = mode === 'before';
async function api(route) {
  const boot = await (await fetch(url + '/api/bootstrap', { headers: { Connection: 'close' }, signal: AbortSignal.timeout(20000) })).json();
  const response = await fetch(url + '/api' + route, { headers: { 'X-Workbench-Token': boot.token, Connection: 'close' }, signal: AbortSignal.timeout(20000) });
  assert.equal(response.status, 200, route); return response.json();
}
async function inspectorClosed() {
  await new Promise((resolve, reject) => { const socket = net.createConnection({ host: '127.0.0.1', port: 9229 }); socket.setTimeout(1500);
    socket.once('connect', () => { socket.destroy(); reject(Error('Inspector is already open.')); });
    socket.once('error', error => { socket.destroy(); error.code === 'ECONNREFUSED' ? resolve() : reject(error); });
    socket.once('timeout', () => { socket.destroy(); reject(Error('Inspector state unknown.')); }); });
}
const startedAt = new Date().toISOString(); let result;
try {
  await inspectorClosed(); const host = await api('/host/status'), dataRoot = host.identity.dataRoot;
  assert.equal(host.identity.pid, 36552); assert.equal(host.activity.active, false);
  assert.equal(host.desktopWindows.count, 0);
  const installRoot = path.dirname(path.dirname(host.identity.runtimeRoot));
  assert.equal(path.basename(path.dirname(host.identity.runtimeRoot)), 'versions');
  const current = await publicSnapshot(url, dataRoot);
  assert.equal(current.pid, 36552); assert.equal(current.hasKey, true); assert.deepEqual(current.active, []);
  if (baseline) {
    assert.equal(current.version, '1.25.1');
    save('state-before.json', current); save('host-before.json', host); save('pointer-before.json', read(path.join(installRoot, 'current.json')));
    result = { success: true, version: current.version, pid: current.pid, dataRoot, installRoot, projects: current.projects,
      sessions: current.database.sessionIds.length, desktopWindows: host.desktopWindows.count, eventCursor: current.eventCursor,
      tables: Object.fromEntries(Object.entries(current.database.tables).map(([name, table]) => [name, table.count])) };
  } else {
    const before = read(path.join(root, 'state-before.json')); compareOriginalState(before, current);
    const candidate = read('releases/latest.json');
    assert.equal(candidate.documentation.sourceCommit, sourceCommit, 'Candidate must be built from the reviewed HEAD.');
    assert.equal(read(path.join(candidate.portableRoot, 'MANIFEST.json')).version, '1.25.2');
    // Reject a stale compiled version before touching the formal host.
    const served = /APP_VERSION\s*=\s*["']([0-9.]+)["']/.exec(fs.readFileSync(path.join(candidate.portableRoot, 'dist-server', 'server.mjs'), 'utf8'));
    assert.equal(served?.[1], '1.25.2', 'Compiled server must report the candidate version.');
    if (mode === 'upgrade') {
      assert.equal(current.version, before.version);
      assert.deepEqual(read(path.join(installRoot, 'current.json')), read(path.join(root, 'pointer-before.json')));
      assert.equal(hash(fs.readFileSync(candidate.installer.path)), candidate.installer.sha256, 'Installer drifted from latest.json.');
      save('candidate.json', candidate); save('preinstall-state.json', current);
      const operationStartedAt = Date.now();
      const fd = fs.openSync(path.join(root, 'installer-process.log'), 'wx'); let code;
      try {
        code = await new Promise((resolve, reject) => {
          const child = spawn(candidate.installer.path, ['/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART',
            '/LOG=' + path.join(root, 'installer.log'), '/DIR=' + installRoot, '/DATA_ROOT=' + dataRoot, '/PORT=4318'],
            { windowsHide: true, stdio: ['ignore', fd, fd] });
          child.once('error', reject); child.once('close', resolve);
        });
      } finally { fs.closeSync(fd); }
      const operationElapsedMs = Date.now() - operationStartedAt;
      save('installer-exit.json', { code, operationElapsedMs, finishedAt: new Date().toISOString() });
      assert.equal(code, 0, 'Do not replay a failed/unknown formal installation.');
    } else {
      assert.equal(read(path.join(root, 'upgrade.json')).success, true);
      assert.deepEqual(candidate, read(path.join(root, 'candidate.json')));
    }
    const after = await publicSnapshot(url, dataRoot), retention = compareOriginalState(before, after), afterHost = await api('/host/status');
    assert.equal(after.version, '1.25.2'); assert.equal(after.pid, before.pid);
    assert.equal(afterHost.identity.instanceId, read(path.join(root, 'host-before.json')).identity.instanceId);
    const installed = path.join(installRoot, 'versions', path.basename(candidate.portableRoot));
    assert.equal(fs.realpathSync.native(after.runtimeRoot), fs.realpathSync.native(installed));
    const identity = inspectHostInstallation(installed), pointer = read(path.join(installRoot, 'current.json'));
    assert.equal(pointer.active.directory, path.basename(installed));
    assert.equal(pointer.active.manifestSha256, identity.manifestSha256);
    assert.equal(pointer.active.runtimeIdentity, identity.identitySha256);
    const operation = fs.readdirSync(path.join(installRoot, '.installation')).filter(name => /^progress-.*\.json$/.test(name))
      .map(name => read(path.join(installRoot, '.installation', name))).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))[0];
    assert.equal(operation.state, 'completed'); assert.equal(operation.candidate.manifestSha256, identity.manifestSha256);
    await inspectorClosed();
    save(mode + '-state-after.json', after);
    result = { success: true, version: after.version, pid: after.pid, runtimeRoot: after.runtimeRoot,
      projects: after.projects, sessions: after.database.sessionIds.length, hasKey: after.hasKey, retention,
      pointerRevision: pointer.revision, previous: pointer.previous?.version, operationState: operation.state,
      inspectorClosed: true, desktopWindows: afterHost.desktopWindows.count };
  }
} catch (error) { result = { success: false, error: error.stack }; process.exitCode = 1; }
result = { ...result, mode, startedAt, finishedAt: new Date().toISOString(), realModelRequests: 0, keyReadOrResaved: false };
save(mode + '.json', result);
console.log(JSON.stringify({ success: result.success, mode, version: result.version, pid: result.pid, error: result.error }, null, 2));
