import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { setTimeout as delay } from 'node:timers/promises';

export const SUPPORTED_UPGRADE_VERSIONS = Object.freeze([
  '0.1.0', '1.0.0', '1.1.0', '1.2.0', '1.3.0', '1.4.0', '1.5.0', '1.5.1',
  '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1',
  '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0',
  '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.20.2', '1.20.3', '1.21.0', '1.22.0',
  '1.22.1', '1.23.0', '1.24.0', '1.24.1', '1.24.2', '1.24.3', '1.24.4', '1.24.5',
  '1.24.6', '1.24.7', '1.24.8', '1.24.9', '1.25.0', '1.25.1', '1.25.2',
]);

function localUrl(value) {
  const url = new URL(value);
  if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1' || url.username || url.password || url.search || url.hash) throw new Error('Upgrade only accepts the local Workbench address.');
  return url.origin;
}

async function within(promise, milliseconds, label) {
  let timer;
  try { return await Promise.race([promise, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(label + ' timed out.')), milliseconds); })]); }
  finally { clearTimeout(timer); }
}

async function readUpgradeJson(address, milliseconds, stage) {
  try {
    // Inspector pauses can outlast a server's keep-alive timeout. Use a fresh
    // connection for each control request rather than reuse a stale pooled one.
    const response = await fetch(address, { headers: { Connection: 'close' }, signal: AbortSignal.timeout(milliseconds) });
    if (!response.ok) throw new Error('HTTP ' + response.status);
    return await response.json();
  } catch (error) {
    throw new Error(stage + ': ' + error.message + (error.cause?.code ? ' (' + error.cause.code + ')' : ''), { cause: error });
  }
}

class Protocol {
  constructor(socket) {
    this.socket = socket; this.nextId = 1; this.pending = new Map(); this.listeners = new Map();
    socket.addEventListener('message', event => {
      const message = JSON.parse(String(event.data));
      if (message.id) {
        const pending = this.pending.get(message.id); if (!pending) return;
        this.pending.delete(message.id);
        if (message.error) pending.reject(new Error(message.error.message)); else pending.resolve(message.result);
      } else for (const listener of this.listeners.get(message.method) ?? []) listener(message.params);
    });
    socket.addEventListener('close', () => { for (const pending of this.pending.values()) pending.reject(new Error('Inspector connection closed.')); this.pending.clear(); });
  }
  on(method, listener) { this.listeners.set(method, [...(this.listeners.get(method) ?? []), listener]); }
  send(method, params = {}) {
    return within(new Promise((resolve, reject) => {
      const id = this.nextId++; this.pending.set(id, { resolve, reject }); this.socket.send(JSON.stringify({ id, method, params }));
    }), 10000, method);
  }
}

function sameFile(url, file) {
  try { return path.resolve(fileURLToPath(url)).toLowerCase() === path.resolve(file).toLowerCase(); } catch { return false; }
}
function sameTarget(target, file) {
  if (sameFile(target.url, file)) return true;
  const displayName = path.resolve(file).replaceAll('\\', '_').replaceAll('/', '_');
  return target.title === displayName && target.url === 'file://' + displayName;
}

export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRoot }) {
  const origin = localUrl(url), original = fs.realpathSync.native(currentRoot), next = fs.realpathSync.native(newRoot);
  const originalScript = path.join(original, 'dist-server', 'server.mjs');
  const upgradeScript = path.join(next, 'dist-server', 'hot-upgrade.mjs');
  if (!fs.existsSync(originalScript) || !fs.existsSync(upgradeScript) || !fs.existsSync(path.join(next, 'dist-client', 'index.html'))) throw new Error('Upgrade bundles are incomplete.');
  if (!Number.isInteger(pid) || pid < 1 || pid === process.pid) throw new Error('Invalid target process.');
  const before = await readUpgradeJson(origin + '/api/bootstrap', 5000, 'Read original Workbench');
  if (!before.token || !SUPPORTED_UPGRADE_VERSIONS.includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.');
  if (before.sessions.some(session => ['running', 'awaiting_approval', 'stopping'].includes(session.status))) throw new Error('Wait for existing tasks and approvals before upgrading.');
  let protocol, socket, enabledHere = false, paused = false;
  const breakpoints = [];
  try {
    let targets;
    try { targets = await readUpgradeJson('http://127.0.0.1:9229/json/list', 500, 'Discover inspector'); } catch {}
    if (targets && !targets.some(target => sameTarget(target, originalScript))) throw new Error('The local inspector port belongs to another process.');
    if (!targets) {
      process._debugProcess(pid); enabledHere = true;
      for (let attempt = 0; attempt < 40 && !targets; attempt++) {
        await delay(100);
        try { targets = await readUpgradeJson('http://127.0.0.1:9229/json/list', 500, 'Discover opened inspector'); } catch {}
      }
    }
    const target = targets?.find(item => sameTarget(item, originalScript));
    if (!target || !target.webSocketDebuggerUrl?.startsWith('ws://127.0.0.1:9229/')) throw new Error('The expected Workbench inspector was not found.');
    socket = new WebSocket(target.webSocketDebuggerUrl);
    await within(new Promise((resolve, reject) => { socket.addEventListener('open', resolve, { once: true }); socket.addEventListener('error', reject, { once: true }); }), 10000, 'Inspector connection');
    protocol = new Protocol(socket);
    const scripts = [];
    protocol.on('Debugger.scriptParsed', script => scripts.push(script));
    let pausedResolve;
    const pausedEvent = new Promise(resolve => { pausedResolve = resolve; });
    protocol.on('Debugger.paused', event => { paused = true; pausedResolve(event); });
    await protocol.send('Runtime.enable');
    const identity = await protocol.send('Runtime.evaluate', { expression: 'process.pid', returnByValue: true });
    if (identity.result.value !== pid) throw new Error('The inspector belongs to a different process.');
    await protocol.send('Debugger.enable');
    const previousRoot = handlerRoot || before.runtimeRoot;
    const expectedScripts = [originalScript, ...(previousRoot ? [path.join(fs.realpathSync.native(previousRoot), 'dist-server', 'hot-upgrade.mjs')] : [])];
    const candidates = scripts.filter(item => expectedScripts.some(file => sameFile(item.url, file)));
    if (!candidates.length) throw new Error('The existing server module is missing from inspector metadata.');
    for (const script of candidates) {
      const { scriptSource } = await protocol.send('Debugger.getScriptSource', { scriptId: script.scriptId });
      // Bundled transport libraries can parse request.url too. Select the
      // actual loopback handler with its local base and observed port binding.
      const locations = scriptSource.split('\n').flatMap((line, index) => /const url = new URL\(request\.url,\s*["']http:\/\/127\.0\.0\.1:["']\s*\+\s*actualPort\d*\)/.test(line) ? [index] : []);
      if (locations.length !== 1) throw new Error('The existing request handler could not be identified uniquely.');
      breakpoints.push((await protocol.send('Debugger.setBreakpoint', { location: { scriptId: script.scriptId, lineNumber: locations[0] } })).breakpointId);
    }
    const probe = readUpgradeJson(origin + '/api/health', 15000, 'Observe owned request handler');
    probe.catch(() => {});
    const event = await within(pausedEvent, 10000, 'Workbench request observation');
    const captureExpression = "(() => {"
      + " const currentServer = typeof server !== 'undefined' ? server : typeof server2 !== 'undefined' ? server2 : undefined;"
      + " const currentStore = typeof store !== 'undefined' ? store : typeof store2 !== 'undefined' ? store2 : undefined;"
      + " const currentProvider = typeof provider !== 'undefined' ? provider : typeof provider2 !== 'undefined' ? provider2 : undefined;"
      + " const currentRuntime = typeof runtime !== 'undefined' ? runtime : typeof runtime2 !== 'undefined' ? runtime2 : undefined;"
      + " const currentToken = typeof token !== 'undefined' ? token : typeof token2 !== 'undefined' ? token2 : undefined;"
      + " const currentClients = typeof clients !== 'undefined' ? clients : typeof clients2 !== 'undefined' ? clients2 : undefined;"
      + " const currentStarted = typeof started !== 'undefined' ? started : typeof started2 !== 'undefined' ? started2 : undefined;"
      + " const currentExampleProject = typeof exampleProject !== 'undefined' ? exampleProject : typeof exampleProject2 !== 'undefined' ? exampleProject2 : undefined;"
      + " const currentShutdown = typeof shutdown !== 'undefined' ? shutdown : typeof shutdown2 !== 'undefined' ? shutdown2 : undefined;"
      + " const servers = currentServer ? [currentServer] : process._getActiveHandles().filter(handle => handle?.listening && handle.address?.()?.address === '127.0.0.1' && handle.address?.()?.port === " + new URL(origin).port + ");"
      + " if (servers.length !== 1 || !currentStore || !currentProvider || !currentRuntime || !currentToken || !currentClients || !currentShutdown) throw new Error('The existing Workbench context is incomplete.');"
      + " globalThis.__awUpgradeContext = { server: servers[0], store: currentStore, provider: currentProvider, runtime: currentRuntime, token: currentToken, clients: currentClients, started: currentStarted, exampleProject: currentExampleProject, shutdown: currentShutdown }; return 'context-ready'; })()";
    const captured = await protocol.send('Debugger.evaluateOnCallFrame', { callFrameId: event.callFrames[0].callFrameId,
      expression: captureExpression, returnByValue: true });
    if (captured.exceptionDetails || captured.result.value !== 'context-ready') throw new Error('Could not retain the existing runtime objects.');
    for (const breakpointId of breakpoints.splice(0)) await protocol.send('Debugger.removeBreakpoint', { breakpointId });
    await protocol.send('Debugger.resume'); paused = false; await probe;
    const expression = '(() => { try { const module = process.getBuiltinModule("module").createRequire(' + JSON.stringify(upgradeScript) + ')(' + JSON.stringify(upgradeScript) + '); return module.installUpgrade(globalThis.__awUpgradeContext, { appDirectory: ' + JSON.stringify(next) + ' }); } finally { delete globalThis.__awUpgradeContext; } })()';
    const upgraded = await protocol.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
    if (upgraded.exceptionDetails) throw new Error('Runtime upgrade failed: ' + (upgraded.exceptionDetails.exception?.description ?? upgraded.exceptionDetails.text));
    const result = upgraded.result.value;
    const after = await readUpgradeJson(origin + '/api/bootstrap', 5000, 'Read upgraded Workbench');
    const health = await readUpgradeJson(origin + '/api/health', 5000, 'Verify upgraded PID');
    if (health.pid !== pid || result.pid !== pid || after.version !== result.version || after.config.hasKey !== before.config.hasKey
      || after.config.model !== before.config.model || after.config.baseUrl !== before.config.baseUrl
      || JSON.stringify(after.projects) !== JSON.stringify(before.projects)
      || JSON.stringify(after.sessions) !== JSON.stringify(before.sessions)) throw new Error('The upgraded runtime did not preserve the existing state.');
    return { ...result, verified: true, connectionPreserved: true, url: origin };
  } finally {
    if (protocol) {
      for (const breakpointId of breakpoints) { try { await protocol.send('Debugger.removeBreakpoint', { breakpointId }); } catch {} }
      try { if (paused) await protocol.send('Debugger.resume'); } catch {}
      try { await protocol.send('Runtime.evaluate', { expression: 'delete globalThis.__awUpgradeContext; true', returnByValue: true }); } catch {}
      if (enabledHere) {
        try { await protocol.send('Runtime.evaluate', { expression: "setTimeout(() => process.getBuiltinModule('inspector').close(), 25); true", returnByValue: true }); } catch {}
      }
    }
    socket?.close();
    if (enabledHere) await delay(150);
  }
}

// This file is also bundled as an installation library; its CLI must not run
// merely because esbuild gives it the install-manager entry's import.meta.url.
if (path.basename(fileURLToPath(import.meta.url)) === 'upgrade-running.mjs' && process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  const raw = process.argv.slice(2), args = {}, options = new Set(['url', 'pid', 'current-root', 'new-root', 'handler-root']);
  if (raw.length === 1 && raw[0] === '--help') { console.log('node scripts/upgrade-running.mjs --pid PID --current-root DIR --new-root DIR [--url http://127.0.0.1:4318] [--handler-root DIR]'); process.exit(0); }
  for (let index = 0; index < raw.length; index += 2) {
    const key = raw[index].startsWith('--') ? raw[index].slice(2) : '';
    if (!options.has(key) || Object.hasOwn(args, key) || !raw[index + 1] || raw[index + 1].startsWith('--')) throw new Error('Unknown or incomplete argument; use --help.');
    args[key] = raw[index + 1];
  }
  if (!/^\d+$/.test(args.pid ?? '') || !path.isAbsolute(args['current-root'] ?? '') || !path.isAbsolute(args['new-root'] ?? '')
    || args['handler-root'] !== undefined && !path.isAbsolute(args['handler-root'])) throw new Error('PID and absolute current/new roots are required arguments; use --help.');
  const result = await upgradeRunning({ url: args.url || 'http://127.0.0.1:4318', pid: Number(args.pid), currentRoot: args['current-root'], newRoot: args['new-root'], handlerRoot: args['handler-root'] });
  console.log(JSON.stringify(result, null, 2));
}
