import path from 'node:path';
import { appendJsonl, ensureDir, nowIso } from '../fsx.js';
const sessions = new Map();
export async function runFakeZellij(args = [], opts = {}) {
    const env = { ...process.env, ...(opts.env || {}) };
    const root = path.resolve(String(env.SKS_ZELLIJ_FAKE_ROOT || opts.cwd || process.cwd()));
    const version = String(env.SKS_ZELLIJ_FAKE_VERSION || '0.43.1');
    const delayMs = Math.max(0, Number(env.SKS_ZELLIJ_FAKE_DELAY_MS || 0) || 0);
    const sessionName = sessionFromArgs(args);
    const startedAt = Date.now();
    let result;
    if (args.length === 1 && args[0] === '--version') {
        result = ok(`zellij ${version}\n`);
    }
    else if (args[0] === 'attach' && args[1] === '--create-background') {
        getSession(String(args[2] || 'default'));
        result = ok('');
    }
    else if (args.includes('new-pane')) {
        if (args.includes('--stacked') && !supportsStacked(version)) {
            result = fail('unknown option --stacked');
        }
        else {
            if (delayMs > 0)
                await sleep(delayMs);
            const session = getSession(sessionName);
            const name = optionValue(args, '--name') || `pane-${session.next_id}`;
            const paneId = `terminal_${session.next_id++}`;
            const command = commandAfter(args, '--') || '';
            const pane = { pane_id: paneId, title: name, name, terminal_command: command, exited: false };
            session.panes.push(pane);
            session.focused_pane_id = paneId;
            result = ok(`${JSON.stringify({ pane_id: paneId })}\n`);
        }
    }
    else if (args.includes('focus-pane-id')) {
        const paneId = String(args[args.indexOf('focus-pane-id') + 1] || '');
        const session = getSession(sessionName);
        const pane = findPane(session, paneId);
        if (!pane)
            result = fail(`Pane ${paneId} not found`);
        else {
            session.focused_pane_id = pane.pane_id;
            result = ok('');
        }
    }
    else if (args.includes('list-panes')) {
        const session = getSession(sessionName);
        result = ok(`${JSON.stringify(session.panes)}\n`);
    }
    else if (args.includes('dump-screen')) {
        const session = getSession(sessionName);
        result = ok(session.panes.map((pane) => pane.title).join('\n') + '\n');
    }
    else if (args.includes('rename-pane')) {
        const session = getSession(sessionName);
        const paneId = optionValue(args, '--pane-id');
        const name = String(args[args.length - 1] || '');
        const pane = paneId ? findPane(session, paneId) : session.panes.find((row) => row.pane_id === session.focused_pane_id);
        if (!pane)
            result = fail(`Pane ${paneId || 'focused'} not found`);
        else {
            pane.title = name;
            pane.name = name;
            result = ok('');
        }
    }
    else if (args.includes('close-pane')) {
        const session = getSession(sessionName);
        const paneId = optionValue(args, '--pane-id');
        const pane = paneId ? findPane(session, paneId) : session.panes.find((row) => row.pane_id === session.focused_pane_id);
        if (!pane)
            result = fail(`Pane ${paneId || 'focused'} not found`);
        else {
            pane.exited = true;
            result = ok('');
        }
    }
    else {
        result = ok('');
    }
    await recordFakeZellijCall(root, args, {
        session_name: sessionName,
        version,
        exit_code: result.code,
        duration_ms: Date.now() - startedAt
    });
    return result;
}
async function recordFakeZellijCall(root, args, meta) {
    const file = path.join(root, '.sneakoscope', 'fake-zellij-calls.jsonl');
    await ensureDir(path.dirname(file));
    await appendJsonl(file, {
        schema: 'sks.fake-zellij-call.v1',
        ts: nowIso(),
        args: [...args],
        ...meta
    });
}
function getSession(name) {
    const key = String(name || 'default');
    const existing = sessions.get(key);
    if (existing)
        return existing;
    const next = { next_id: 1, focused_pane_id: null, panes: [] };
    sessions.set(key, next);
    return next;
}
function sessionFromArgs(args) {
    const explicit = optionValue(args, '--session');
    if (explicit)
        return explicit;
    if (args[0] === 'attach' && args[1] === '--create-background')
        return String(args[2] || 'default');
    return 'default';
}
function optionValue(args, flag) {
    const index = args.indexOf(flag);
    if (index < 0)
        return null;
    const value = args[index + 1];
    return value == null ? null : String(value);
}
function commandAfter(args, marker) {
    const index = args.indexOf(marker);
    if (index < 0)
        return null;
    return args.slice(index + 1).map(String).join(' ');
}
function findPane(session, id) {
    const normalized = String(id || '').replace(/^terminal_/, '');
    return session.panes.find((pane) => pane.pane_id === id || pane.pane_id.replace(/^terminal_/, '') === normalized) || null;
}
function supportsStacked(version) {
    const parts = String(version || '0.0.0').match(/(\d+)\.(\d+)\.(\d+)/)?.slice(1).map((part) => Number.parseInt(part, 10) || 0) || [0, 0, 0];
    return parts[0] > 0 || parts[1] > 43 || (parts[1] === 43 && parts[2] >= 0);
}
function ok(stdout) {
    return {
        code: 0,
        stdout,
        stderr: '',
        stdoutBytes: Buffer.byteLength(stdout),
        stderrBytes: 0,
        truncated: false,
        timedOut: false
    };
}
function fail(stderr) {
    return {
        code: 1,
        stdout: '',
        stderr,
        stdoutBytes: 0,
        stderrBytes: Buffer.byteLength(stderr),
        truncated: false,
        timedOut: false
    };
}
function sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}
//# sourceMappingURL=zellij-fake-adapter.js.map