/**
 * Playwright Chromium bootstrap for server deploys.
 *
 * `inspect_artifact` and the artifact PDF/PNG export render through Playwright's
 * Chromium. A bare Node host (e.g. the Railway `node:20` image) ships neither the
 * Chromium browser nor the OS libraries it needs, so those tools fail with
 * "Install the Playwright Chromium runtime with: npx playwright install chromium".
 *
 * This ensures the runtime is present WITHOUT blocking server startup:
 *   - Opt-in via `STUDIOGRAPH_INSTALL_PLAYWRIGHT=1` (the deploy sets it; local
 *     `studiograph serve` stays lean and never downloads ~150MB unprompted).
 *   - Runs in the background after the server is already listening, so first
 *     requests aren't delayed; inspect/export light up a minute or so after boot.
 *   - `npx playwright install --with-deps chromium` is idempotent — it skips an
 *     already-downloaded browser and re-checks the apt deps (needs root, which
 *     Railway provides). Set `STUDIOGRAPH_PLAYWRIGHT_BROWSER_ONLY=1` to drop
 *     `--with-deps` when the OS libs are already baked into the image.
 *   - Point `PLAYWRIGHT_BROWSERS_PATH` at a persistent volume so the browser
 *     downloads once instead of on every cold boot.
 *
 * Best-effort throughout: any failure is logged and swallowed — the worst case is
 * the pre-existing "inspect unavailable" behavior, never a crashed boot.
 */
import { spawn } from 'node:child_process';
import { existsSync } from 'node:fs';
let kicked = false;
export function ensurePlaywrightChromium(log = console.log) {
    if (kicked)
        return; // one attempt per process
    kicked = true;
    if (process.env.STUDIOGRAPH_INSTALL_PLAYWRIGHT !== '1')
        return;
    const browserOnly = process.env.STUDIOGRAPH_PLAYWRIGHT_BROWSER_ONLY === '1';
    void (async () => {
        try {
            // Browser-only mode trusts the image for OS libs, so a cached browser is
            // enough — skip the install entirely on warm volumes.
            if (browserOnly) {
                try {
                    const pw = await import('playwright');
                    const exe = pw.chromium.executablePath();
                    if (exe && existsSync(exe)) {
                        log('[playwright] chromium already present — skipping install');
                        return;
                    }
                }
                catch {
                    // playwright package or executablePath unavailable → fall through to install.
                }
            }
            const args = browserOnly
                ? ['--yes', 'playwright', 'install', 'chromium']
                : ['--yes', 'playwright', 'install', '--with-deps', 'chromium'];
            log(`[playwright] ensuring chromium runtime in the background (npx ${args.join(' ')})…`);
            await new Promise((resolve) => {
                const child = spawn('npx', args, { stdio: 'inherit', env: process.env });
                child.on('exit', (code) => {
                    log(code === 0
                        ? '[playwright] chromium runtime ready — inspect_artifact/export enabled'
                        : `[playwright] chromium install exited ${code ?? 'null'} (inspect_artifact stays unavailable)`);
                    resolve();
                });
                child.on('error', (err) => {
                    log(`[playwright] chromium install could not start: ${err.message}`);
                    resolve();
                });
            });
        }
        catch (err) {
            log(`[playwright] chromium bootstrap failed (inspect_artifact stays unavailable): ${err instanceof Error ? err.message : String(err)}`);
        }
    })();
}
//# sourceMappingURL=playwright-bootstrap.js.map