"use strict";
/**
 * console-query — single-turn Claude call for the ConsoleView.
 *
 * Uses the global agent (getAgent) so all calls share the same initialized
 * SDK config (gateway URL, model, env) rather than making raw fetch calls.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveConsoleCredentials = resolveConsoleCredentials;
exports.buildSessionContext = buildSessionContext;
exports.queryConsole = queryConsole;
const urls_js_1 = require("../utils/urls.js");
const wizard_session_js_1 = require("./wizard-session.js");
const agent_interface_js_1 = require("./agent-interface.js");
const schemas_js_1 = require("./middleware/schemas.js");
const wizard_tools_js_1 = require("./wizard-tools.js");
/** Resolve credentials from session + env, in priority order. */
function resolveConsoleCredentials(session) {
    // Gateway: set after initializeAgent runs
    if (process.env.ANTHROPIC_BASE_URL && process.env.ANTHROPIC_AUTH_TOKEN) {
        return {
            kind: 'gateway',
            baseUrl: process.env.ANTHROPIC_BASE_URL,
            apiKey: process.env.ANTHROPIC_AUTH_TOKEN,
        };
    }
    // Session credentials: available after auth screen
    if (session.credentials?.projectApiKey && session.credentials?.host) {
        return {
            kind: 'gateway',
            baseUrl: (0, urls_js_1.getLlmGatewayUrlFromHost)(session.credentials.host),
            apiKey: session.credentials.projectApiKey,
        };
    }
    // Direct Anthropic API key
    if (process.env.ANTHROPIC_API_KEY) {
        return { kind: 'direct', apiKey: process.env.ANTHROPIC_API_KEY };
    }
    return { kind: 'none' };
}
/** Build a compact plain-text summary of the current session state for the system prompt. */
function buildSessionContext(session) {
    const lines = [
        'You are a helpful assistant embedded in the Amplitude Wizard CLI.',
        "Answer the user's questions concisely. Focus on the current wizard state below.",
        '',
        '--- Current wizard state ---',
        `Phase: ${session.runPhase ?? wizard_session_js_1.RunPhase.Idle}`,
    ];
    if (session.region)
        lines.push(`Region: ${session.region}`);
    if (session.detectedFrameworkLabel)
        lines.push(`Framework: ${session.detectedFrameworkLabel}`);
    if (session.integration)
        lines.push(`Integration: ${session.integration}`);
    if (session.selectedOrgName)
        lines.push(`Org: ${session.selectedOrgName}`);
    if (session.selectedProjectName)
        lines.push(`Project: ${session.selectedProjectName}`);
    // Amplitude's UI labels this "Project ID" — keep user-facing label familiar
    // even though the canonical code term is `appId`.
    if (session.credentials?.appId)
        lines.push(`Project ID: ${session.credentials.appId}`);
    if (session.runPhase === wizard_session_js_1.RunPhase.Completed) {
        lines.push('Status: Wizard run completed successfully.');
    }
    else if (session.runPhase === wizard_session_js_1.RunPhase.Error) {
        lines.push('Status: Wizard run finished with an error.');
    }
    else if (session.runPhase === wizard_session_js_1.RunPhase.Running) {
        lines.push('Status: Wizard agent is currently running.');
    }
    if (session.outroData?.message) {
        lines.push(`Last message: ${session.outroData.message}`);
    }
    return lines.join('\n');
}
/** Send a message to Claude with optional conversation history and return the text response. */
async function queryConsole(userMessage, sessionContext, creds, history = []) {
    if (creds.kind === 'none') {
        return 'Claude is not available yet — complete authentication first.';
    }
    const agentConfig = await (0, agent_interface_js_1.getAgent)();
    const { query } = (await import('@anthropic-ai/claude-agent-sdk'));
    const historyBlock = history.length > 0
        ? '\n\n--- Conversation history ---\n' +
            history
                .map((t) => `${t.role === 'user' ? 'User' : 'Assistant'}: ${t.content}`)
                .join('\n') +
            '\n--- End of history ---'
        : '';
    const collectedText = [];
    // Forward x-amp-wizard-session-id so slash-prompt LLM calls land in the
    // SAME Agent Analytics session as the main agent run, instead of falling
    // through to the proxy's per-token-hash fallback (which would collapse all
    // slash-prompt queries across every wizard run a user has ever done into
    // one synthetic session).
    //
    // We rebuild ANTHROPIC_CUSTOM_HEADERS here rather than read from process.env
    // because the SDK subprocess sets the env scoped to its query() call —
    // process.env never sees the value the main run injected.
    const customHeaders = (0, agent_interface_js_1.buildAgentEnv)({}, {}, agentConfig.agentSessionId);
    const response = query({
        prompt: userMessage,
        options: {
            model: agentConfig.model,
            cwd: agentConfig.workingDirectory,
            permissionMode: 'bypassPermissions',
            mcpServers: agentConfig.mcpServers,
            allowedTools: wizard_tools_js_1.WIZARD_TOOL_NAMES,
            systemPrompt: sessionContext + historyBlock,
            env: {
                ...process.env,
                ANTHROPIC_CUSTOM_HEADERS: customHeaders,
            },
        },
    });
    for await (const rawMessage of response) {
        const parsed = (0, schemas_js_1.safeParseSDKMessage)(rawMessage);
        if (!parsed.ok)
            continue;
        const message = parsed.message;
        if (message.type === 'assistant') {
            const content = message.message?.content;
            if (Array.isArray(content)) {
                for (const block of content) {
                    if (block.type === 'text' && typeof block.text === 'string') {
                        collectedText.push(block.text);
                    }
                }
            }
        }
    }
    return collectedText.join('') || '(empty response)';
}
