import { spawn, spawnSync } from 'node:child_process';
import path from 'node:path';

type Logger = {
  info?: (message: string) => void;
  warn?: (message: string) => void;
  error?: (message: string) => void;
};

type StartWikiHelperParams = {
  accountId: string;
  parallUrl: string;
  apiKey: string;
  orgId: string;
  agentId: string;
  stateDir: string;
  log?: Logger;
};

type WikiHelperRuntime = {
  mountRoot: string;
  stop: () => void;
};

const DEFAULT_SYNC_TIMEOUT_MS = 90_000; // includes npx cold-start download time
const DEFAULT_WATCH_INTERVAL_SEC = 30;

function isCommandMissing(error: unknown): boolean {
  return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT';
}

// Prefer bare `parall` (globally installed in hosted images). Fall back to
// npx for self-hosted environments that haven't installed @parall/cli yet.
let _cli: { cmd: string; prefix: string[] } | undefined;
function resolveParallCli(): { cmd: string; prefix: string[] } {
  if (!_cli) {
    const r = spawnSync('parall', ['--version'], { stdio: 'ignore', timeout: 5_000 });
    _cli = r.error
      ? { cmd: 'npx', prefix: ['--yes', '@parall/cli@latest'] }
      : { cmd: 'parall', prefix: [] };
  }
  return _cli;
}

function resolveMountRoot(stateDir: string): string {
  return process.env.PRLL_WIKI_MOUNT_ROOT?.trim() || path.join(stateDir, 'workspace');
}

function resolveWatchIntervalSec(): number {
  const raw = process.env.PRLL_WIKI_REFRESH_INTERVAL_SEC?.trim();
  if (!raw) {
    return DEFAULT_WATCH_INTERVAL_SEC;
  }
  const parsed = Number.parseInt(raw, 10);
  return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_WATCH_INTERVAL_SEC;
}

function buildWikiHelperEnv(params: StartWikiHelperParams, mountRoot: string): NodeJS.ProcessEnv {
  return {
    ...process.env,
    PRLL_API_URL: params.parallUrl,
    PRLL_API_KEY: params.apiKey,
    PRLL_ORG_ID: params.orgId,
    PRLL_AGENT_ID: params.agentId,
    PRLL_WIKI_MOUNT_ROOT: mountRoot,
  };
}

async function runWikiSync(
  params: StartWikiHelperParams,
  env: NodeJS.ProcessEnv,
): Promise<'ok' | 'missing' | 'failed'> {
  return new Promise((resolve) => {
    let timedOut = false;
    let settled = false;

    const { cmd, prefix } = resolveParallCli();
    const child = spawn(cmd, [...prefix, 'wiki', 'sync'], {
      env,
      stdio: 'ignore',
    });

    const settle = (value: 'ok' | 'missing' | 'failed') => {
      if (settled) return;
      settled = true;
      resolve(value);
    };

    const timer = setTimeout(() => {
      timedOut = true;
      params.log?.warn?.(
        `parall[${params.accountId}]: parall sync timed out after ${DEFAULT_SYNC_TIMEOUT_MS}ms`,
      );
      child.kill('SIGTERM');
      setTimeout(() => child.kill('SIGKILL'), 5_000).unref();
    }, DEFAULT_SYNC_TIMEOUT_MS);
    timer.unref();

    child.on('error', (error) => {
      clearTimeout(timer);
      if (isCommandMissing(error)) {
        params.log?.warn?.(
          `parall[${params.accountId}]: parall not installed, skipping wiki auto-sync/watch`,
        );
        settle('missing');
        return;
      }
      params.log?.warn?.(
        `parall[${params.accountId}]: parall sync failed to start: ${String(error)}`,
      );
      settle('failed');
    });

    child.on('exit', (code, signal) => {
      clearTimeout(timer);
      if (timedOut) {
        settle('failed');
        return;
      }
      if (code === 0) {
        params.log?.info?.(`parall[${params.accountId}]: parall sync completed`);
        settle('ok');
        return;
      }
      params.log?.warn?.(
        `parall[${params.accountId}]: parall sync exited with code=${code ?? 'null'} signal=${signal ?? 'null'}`,
      );
      settle('failed');
    });
  });
}

export async function startWikiHelper(params: StartWikiHelperParams): Promise<WikiHelperRuntime> {
  const mountRoot = resolveMountRoot(params.stateDir);
  const env = buildWikiHelperEnv(params, mountRoot);

  const syncResult = await runWikiSync(params, env);
  if (syncResult === 'missing') {
    return {
      mountRoot,
      stop() {},
    };
  }

  const intervalSec = resolveWatchIntervalSec();
  let stopped = false;
  const { cmd, prefix } = resolveParallCli();
  const watch = spawn(cmd, [...prefix, 'wiki', 'watch', '--interval-sec', String(intervalSec)], {
    env,
    stdio: 'ignore',
  });

  watch.on('error', (error) => {
    if (stopped) return;
    if (isCommandMissing(error)) {
      params.log?.warn?.(
        `parall[${params.accountId}]: parall disappeared before watch could start`,
      );
      return;
    }
    params.log?.warn?.(`parall[${params.accountId}]: parall watch failed: ${String(error)}`);
  });

  watch.on('exit', (code, signal) => {
    if (stopped) return;
    params.log?.warn?.(
      `parall[${params.accountId}]: parall watch exited with code=${code ?? 'null'} signal=${signal ?? 'null'}`,
    );
  });

  params.log?.info?.(
    `parall[${params.accountId}]: parall watch started (interval=${intervalSec}s)`,
  );

  return {
    mountRoot,
    stop() {
      stopped = true;
      if (watch.exitCode === null && watch.signalCode === null) {
        watch.kill('SIGTERM');
        setTimeout(() => watch.kill('SIGKILL'), 5_000).unref();
      }
    },
  };
}
