"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.listTools = exports.initializeMcpSession = exports.buildMcpHeaders = exports.assertResponseStatus = void 0;
const test_1 = require("@playwright/test");
async function assertResponseStatus(res, expected, label) {
    const matches = Array.isArray(expected)
        ? expected.includes(res.status())
        : res.status() === expected;
    if (!matches) {
        const body = await res.text().catch(() => '<no-body>');
        const expectedStr = Array.isArray(expected)
            ? expected.join('/')
            : String(expected);
        console.error(`${label ?? 'assertResponseStatus'}: expected ${expectedStr} but got ${res.status()}`, body);
    }
    if (Array.isArray(expected)) {
        (0, test_1.expect)(expected).toContain(res.status());
    }
    else {
        (0, test_1.expect)(res.status()).toBe(expected);
    }
}
exports.assertResponseStatus = assertResponseStatus;
function buildMcpHeaders(authToken, mcpSessionId) {
    const headers = {
        Authorization: authToken,
        'Content-Type': 'application/json',
        Accept: 'application/json, text/event-stream',
    };
    if (mcpSessionId)
        headers['Mcp-Session-Id'] = mcpSessionId;
    return headers;
}
exports.buildMcpHeaders = buildMcpHeaders;
async function initializeMcpSession(apiContext, mcpProcessesUrl, authToken, mcpSessionId) {
    const res = await apiContext.post(mcpProcessesUrl, {
        headers: buildMcpHeaders(authToken, mcpSessionId),
        data: {
            jsonrpc: '2.0',
            id: 1,
            method: 'initialize',
            params: {
                protocolVersion: '2024-11-05',
                capabilities: {},
                clientInfo: { name: 'playwright-test', version: '1.0.0' },
            },
        },
    });
    if (res.status() >= 300) {
        const body = await res.text().catch(() => '<no-body>');
        console.error('initializeMcpSession: unexpected HTTP status', res.status(), body);
    }
    (0, test_1.expect)(res.status()).toBeLessThan(300);
    const initBody = await res.json();
    if (initBody.error) {
        console.error('initializeMcpSession: JSON-RPC error on initialize', JSON.stringify(initBody.error));
    }
    (0, test_1.expect)(initBody.error).toBeUndefined();
    (0, test_1.expect)(initBody.result).toBeDefined();
    const newSessionId = res.headers()['mcp-session-id'] ?? null;
    if (!newSessionId) {
        console.warn('initializeMcpSession: server did not return Mcp-Session-Id — running without session (stateless mode)');
    }
    const notifRes = await apiContext.post(mcpProcessesUrl, {
        headers: buildMcpHeaders(authToken, newSessionId),
        data: { jsonrpc: '2.0', method: 'notifications/initialized', params: {} },
    });
    if (notifRes.status() >= 300) {
        const body = await notifRes.text().catch(() => '<no-body>');
        console.error('initializeMcpSession: unexpected HTTP status on notifications/initialized', notifRes.status(), body);
    }
    (0, test_1.expect)(notifRes.status()).toBeLessThan(300);
    return newSessionId;
}
exports.initializeMcpSession = initializeMcpSession;
async function listTools(apiContext, mcpProcessesUrl, authToken, mcpSessionId) {
    const res = await apiContext.post(mcpProcessesUrl, {
        headers: buildMcpHeaders(authToken, mcpSessionId),
        data: { jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} },
    });
    if (res.status() !== 200) {
        const body = await res.text().catch(() => '<no-body>');
        console.error('listTools: unexpected HTTP status', res.status(), body);
    }
    (0, test_1.expect)(res.status()).toBe(200);
    const body = await res.json();
    if (body.error) {
        console.error('listTools: JSON-RPC error', JSON.stringify(body.error));
    }
    (0, test_1.expect)(body.error).toBeUndefined();
    (0, test_1.expect)(Array.isArray(body.result?.tools)).toBe(true);
    return body.result.tools;
}
exports.listTools = listTools;
