import { CdpClient } from './cdp-client.js';
import { windowKindFromTitle } from './cursor-window-kind.js';
import { extractPageState } from './extract-page.js';
/**
 * Home window: continuous poll via main CDPBridge.
 * Other windows: parallel temporary CDP connections on an interval.
 */
export class WindowMonitor {
    cdpBridge;
    stateManager;
    selectors;
    config;
    cycleTimer = null;
    cycling = false;
    constructor(cdpBridge, stateManager, selectors, config) {
        this.cdpBridge = cdpBridge;
        this.stateManager = stateManager;
        this.selectors = selectors;
        this.config = config;
    }
    start() {
        this.cycleTimer = setInterval(() => void this.cycle(), this.config.windowPollIntervalMs);
        setTimeout(() => void this.cycle(), 2000);
        console.log(`[window-monitor] Parallel poll every ${this.config.windowPollIntervalMs}ms`);
    }
    stop() {
        if (this.cycleTimer)
            clearInterval(this.cycleTimer);
    }
    async cycle() {
        if (this.cycling || !this.cdpBridge.getClient()?.isConnected())
            return;
        this.cycling = true;
        try {
            await this.cdpBridge.refreshWindows();
            const homeId = this.cdpBridge.activeTargetId;
            const snapshots = [];
            for (const win of this.cdpBridge.windows) {
                if (win.id === homeId) {
                    const st = this.stateManager.getState();
                    const last = st.messages[st.messages.length - 1];
                    snapshots.push({
                        windowId: win.id,
                        title: win.title,
                        activeComposerId: st.activeComposerId,
                        messageCount: st.messages.length,
                        lastPreview: last?.text?.slice(0, 80),
                        agentStatus: st.agentStatus,
                        agentWorking: st.agentWorking,
                        tabs: st.tabs,
                        pendingApprovals: st.pendingApprovals?.length ?? 0,
                        updatedAt: Date.now(),
                    });
                    continue;
                }
                if (!win.wsUrl)
                    continue;
                const snap = await this.pollWindow(win.id, win.title, win.wsUrl);
                if (snap)
                    snapshots.push(snap);
            }
            this.stateManager.updateWindowSnapshots(snapshots);
        }
        finally {
            this.cycling = false;
        }
    }
    async pollWindow(windowId, title, wsUrl) {
        const client = new CdpClient();
        try {
            await client.connect(wsUrl);
            const partial = await extractPageState(client, this.selectors);
            if (!partial)
                return null;
            const last = partial.messages[partial.messages.length - 1];
            return {
                windowId,
                title,
                kind: windowKindFromTitle(title),
                tabs: partial.tabs ?? [],
                activeComposerId: partial.activeComposerId,
                messageCount: partial.messages.length,
                lastPreview: last?.text?.slice(0, 80),
                agentStatus: partial.agentStatus,
                agentWorking: partial.agentWorking,
                pendingApprovals: partial.pendingApprovals?.length ?? 0,
                updatedAt: Date.now(),
            };
        }
        catch {
            return null;
        }
        finally {
            client.disconnect();
        }
    }
}
