/**
 * Fetch workbook connection state from the running Excel instance via ShortcutXL.
 *
 * The runtime only needs two facts:
 * - whether Excel is currently connected
 * - which workbook names are open
 */
import { getWorkbookScopeDetails, SCOPE_NONE } from '../workbook-scope.js';
import { getEffectiveExcelHttpUrl } from '../xll/endpoint.js';
import { requireLocalExcelHttpUrl } from '../xll/http-url.js';
import { xllFetch } from '../xll/session.js';
const NAMES_ONLY_CODE = `
if app.Workbooks.Count == 0:
    print("")
else:
    print(",".join([wb.Name for wb in app.Workbooks]))
`.trim();
export function formatWorkbookScopeReminder(details) {
    if (!details.connected) {
        return 'ShortcutXL is not currently connected to Excel.';
    }
    if (details.scopeMode === SCOPE_NONE) {
        return 'ShortcutXL is connected to Excel, but no workbook is currently in scope.';
    }
    if (details.workbooks.length === 0) {
        return 'ShortcutXL is connected to Excel, but no workbook is currently open.';
    }
    return `ShortcutXL is connected to Excel. Workbooks in scope: ${details.workbooks.join(', ')}.`;
}
function resolveWorkbookBaseUrl(httpUrl) {
    try {
        return requireLocalExcelHttpUrl(httpUrl ?? getEffectiveExcelHttpUrl());
    }
    catch {
        return null;
    }
}
async function postWorkbookExecCode(code, httpUrl) {
    const baseUrl = resolveWorkbookBaseUrl(httpUrl);
    if (!baseUrl) {
        return { connected: false, output: null };
    }
    try {
        const response = await xllFetch(`${baseUrl}/exec`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ code }),
            signal: AbortSignal.timeout(3000)
        });
        const result = (await response.json());
        if (!result.ok) {
            return { connected: false, output: null };
        }
        return { connected: true, output: result.output?.trim() ?? '' };
    }
    catch {
        return { connected: false, output: null };
    }
}
function parseWorkbookNames(output) {
    return output
        .split(',')
        .map((name) => name.trim())
        .filter(Boolean);
}
export async function fetchWorkbookConnectionState(httpUrl) {
    const { connected, output } = await postWorkbookExecCode(NAMES_ONLY_CODE, httpUrl);
    return {
        connected,
        workbooks: connected && output ? parseWorkbookNames(output) : []
    };
}
export function buildWorkbookPromptContext(connectionState, scope) {
    const details = getWorkbookScopeDetails(scope, connectionState.workbooks);
    return {
        text: formatWorkbookScopeReminder({
            connected: connectionState.connected,
            workbooks: details.workbooks,
            scopeMode: details.scopeMode
        }),
        details
    };
}
//# sourceMappingURL=workbook-summary.js.map