/**
 * SDK Info Service — Caches account info and supported models from the Agent SDK.
 *
 * Spawns a lightweight query at startup to extract initialization data
 * (account info, supported models) without actually running a conversation.
 * Results are cached for the lifetime of the process.
 */
import { getAgentProvider } from "../agents/factory.js";
import { tmpdir } from "os";
import { createLogger } from "../utils/logger.js";
import { getApiEnvOverrides, getClaudeCodeExecutablePath } from "./agent-settings.js";
const log = createLogger("sdk-info");
let cache = null;
let fetchPromise = null;
/**
 * Fetch account info and supported models from the Agent SDK.
 * Uses a minimal query that is closed immediately after extracting init data.
 */
async function fetchSdkInfo() {
    log.info("Fetching SDK info (account + models)...");
    try {
        // Use streaming input mode so the query waits for input instead of auto-completing
        const inputStream = (async function* () {
            // Yield nothing — we just need the query to initialize
            // and then we'll close it after reading init data
            yield {
                type: "user",
                message: { role: "user", content: "hi" },
                parent_tool_use_id: null,
                session_id: "",
            };
        })();
        const claudeExecutable = getClaudeCodeExecutablePath();
        const conversation = getAgentProvider().query({
            prompt: inputStream,
            options: {
                cwd: tmpdir(),
                ...(claudeExecutable ? { pathToClaudeCodeExecutable: claudeExecutable } : {}),
                tools: [],
                maxTurns: 1,
                persistSession: false,
                settingSources: ["user"],
                permissionMode: "bypassPermissions",
                allowDangerouslySkipPermissions: true,
                env: {
                    ...process.env,
                    // Apply user-configured API / auth / model overrides so the
                    // account + supported models reported here match what the
                    // actual sessions will use.
                    ...getApiEnvOverrides(),
                    CLAUDECODE: undefined,
                },
            },
        });
        // Read init data from the query object
        const [account, models] = await Promise.all([conversation.accountInfo(), conversation.supportedModels()]);
        // Close the query — we don't need to actually run a conversation
        conversation.close();
        const result = {
            account: account || null,
            models: (models || []).map((m) => ({
                value: m.value,
                displayName: m.displayName,
                description: m.description,
            })),
            fetchedAt: Date.now(),
        };
        log.info(`SDK info fetched: ${result.models.length} models, account=${result.account?.email || "unknown"}`);
        return result;
    }
    catch (err) {
        log.error(`Failed to fetch SDK info: ${err.message}`);
        return { account: null, models: [], fetchedAt: Date.now() };
    }
}
/**
 * Initialize the SDK info cache. Call once at startup.
 * Non-blocking — runs in the background.
 */
export function initSdkInfoCache() {
    if (fetchPromise)
        return;
    fetchPromise = fetchSdkInfo().then((result) => {
        cache = result;
        return result;
    });
}
/**
 * Get cached SDK info. Returns null if not yet fetched.
 */
export function getSdkInfo() {
    return cache;
}
/**
 * Get cached SDK info, waiting for the initial fetch if needed.
 */
export async function getSdkInfoAsync() {
    if (cache)
        return cache;
    if (fetchPromise)
        return fetchPromise;
    // If init was never called, do it now
    initSdkInfoCache();
    return fetchPromise;
}
/**
 * Invalidate the cached SDK info and re-fetch with the current env overrides.
 * Called when the user changes API / auth / model override settings so the
 * About page reflects the new account + supported models.
 */
export function refreshSdkInfoCache() {
    cache = null;
    fetchPromise = fetchSdkInfo().then((result) => {
        cache = result;
        return result;
    });
    return fetchPromise;
}
