import { CdpClient } from './cdp-client.js';
const PROBE_TIMEOUT_MS = 2500;
async function probeWindowHasFocus(wsUrl) {
    const client = new CdpClient();
    try {
        await client.connect(wsUrl);
        const value = await client.evaluate('document.hasFocus()', PROBE_TIMEOUT_MS);
        return value === true;
    }
    catch {
        return false;
    }
    finally {
        client.disconnect();
    }
}
/** Which workbench CDP target has keyboard focus (foreground Cursor window). */
export async function detectForegroundTargetId(windows, currentTargetId) {
    const pages = windows.filter((w) => w.wsUrl);
    if (pages.length === 0)
        return null;
    if (pages.length === 1)
        return pages[0].id;
    if (currentTargetId) {
        const current = pages.find((w) => w.id === currentTargetId);
        if (current?.wsUrl) {
            const focused = await probeWindowHasFocus(current.wsUrl);
            if (focused)
                return currentTargetId;
        }
    }
    const probes = await Promise.all(pages.map(async (w) => ({
        id: w.id,
        focused: await probeWindowHasFocus(w.wsUrl),
    })));
    const hits = probes.filter((p) => p.focused);
    if (hits.length === 1)
        return hits[0].id;
    return null;
}
