"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.selectSingleProcessIfPossible = exports.dashboardHasComparisonTile = exports.getReportNumericResult = exports.findReportByName = exports.parseJsonResponseBodies = exports.captureDashboardResponses = exports.isLikelyDashboardApiResponse = exports.isReportEvaluateResponse = exports.isAgenticDashboardDefinitionResponse = exports.changeDashboardDateRange = exports.openAgenticControlPlane = exports.clickFirstVisibleByName = exports.LEGACY_TERMINOLOGY = exports.CURRENT_TERMINOLOGY = exports.EXECUTION_REPORT_NAME = exports.REPORT_EVALUATE_PATH_PATTERN = exports.AGENTIC_DASHBOARD_DEFINITION_PATH = void 0;
const test_1 = require("@playwright/test");
exports.AGENTIC_DASHBOARD_DEFINITION_PATH = '/api/dashboard/agentic';
exports.REPORT_EVALUATE_PATH_PATTERN = /\/api\/report\/[^/]+\/evaluate/;
exports.EXECUTION_REPORT_NAME = 'total executions';
exports.CURRENT_TERMINOLOGY = 'total executions';
exports.LEGACY_TERMINOLOGY = 'completed agent runs';
const candidateDashboardLabels = [
    'Agentic Control Plane',
    'Control Plane',
    'Agentic Dashboard',
];
async function clickFirstVisibleByName(page, role, names) {
    for (const name of names) {
        const locator = page.getByRole(role, { name, exact: false });
        if (await locator
            .first()
            .isVisible({ timeout: 3000 })
            .catch(() => false)) {
            await locator.first().click({ timeout: 20000 });
            return true;
        }
    }
    return false;
}
exports.clickFirstVisibleByName = clickFirstVisibleByName;
async function openAgenticControlPlane(page, appsPage, optimizeHomePage, clusterName) {
    await appsPage.clickCamundaApps();
    await appsPage.clickOptimize(clusterName);
    await test_1.expect
        .poll(async () => optimizeHomePage.optimizeBanner.isVisible({ timeout: 5000 }), {
        timeout: 120000,
    })
        .toBe(true);
    const clickedLink = await clickFirstVisibleByName(page, 'link', candidateDashboardLabels);
    if (!clickedLink) {
        const clickedButton = await clickFirstVisibleByName(page, 'button', candidateDashboardLabels);
        (0, test_1.expect)(clickedButton).toBeTruthy();
    }
}
exports.openAgenticControlPlane = openAgenticControlPlane;
async function changeDashboardDateRange(page) {
    const dateRange = page.locator('.dateRange').first();
    const trigger = dateRange.locator('button.cds--list-box__field').first();
    const triggerReady = await trigger
        .waitFor({ state: 'visible', timeout: 30000 })
        .then(() => true)
        .catch(() => false);
    if (!triggerReady) {
        return false;
    }
    await trigger.click({ timeout: 20000 });
    const menu = page.locator('ul[role="menu"].cds--menu--shown').last();
    const menuReady = await menu
        .waitFor({ state: 'visible', timeout: 10000 })
        .then(() => true)
        .catch(() => false);
    if (!menuReady) {
        return false;
    }
    const options = menu.locator('[role="menuitemcheckbox"]');
    await test_1.expect
        .poll(async () => options.count(), { timeout: 10000 })
        .toBeGreaterThan(0);
    const optionCount = await options.count();
    for (let index = 0; index < optionCount; index += 1) {
        const option = options.nth(index);
        const isChecked = (await option.getAttribute('aria-checked')) === 'true';
        if (!isChecked) {
            await option.click({ timeout: 15000 });
            return true;
        }
    }
    await page.keyboard.press('Escape').catch(() => false);
    return false;
}
exports.changeDashboardDateRange = changeDashboardDateRange;
function isAgenticDashboardDefinitionResponse(response) {
    return response.url.toLowerCase().includes(exports.AGENTIC_DASHBOARD_DEFINITION_PATH);
}
exports.isAgenticDashboardDefinitionResponse = isAgenticDashboardDefinitionResponse;
function isReportEvaluateResponse(response) {
    return exports.REPORT_EVALUATE_PATH_PATTERN.test(response.url.toLowerCase());
}
exports.isReportEvaluateResponse = isReportEvaluateResponse;
function isLikelyDashboardApiResponse(response) {
    return (isAgenticDashboardDefinitionResponse(response) ||
        isReportEvaluateResponse(response));
}
exports.isLikelyDashboardApiResponse = isLikelyDashboardApiResponse;
async function captureDashboardResponses(page, action) {
    const captured = [];
    const listener = async (response) => {
        try {
            const request = response.request();
            const method = request.method();
            if (method !== 'GET' && method !== 'POST')
                return;
            const contentType = response.headers()['content-type'] || '';
            if (!contentType.includes('application/json'))
                return;
            const bodyText = await response.text();
            captured.push({
                url: response.url(),
                method,
                status: response.status(),
                bodyText,
                contentType,
            });
        }
        catch {
            return;
        }
    };
    page.on('response', listener);
    await action();
    await page.waitForLoadState('networkidle', { timeout: 30000 }).catch(() => { });
    await page.waitForTimeout(5000);
    page.off('response', listener);
    return captured;
}
exports.captureDashboardResponses = captureDashboardResponses;
function parseJsonResponseBodies(responses) {
    const parsed = [];
    for (const response of responses) {
        try {
            parsed.push(JSON.parse(response.bodyText));
        }
        catch {
            continue;
        }
    }
    return parsed;
}
exports.parseJsonResponseBodies = parseJsonResponseBodies;
function findReportByName(bodies, name) {
    const target = name.toLowerCase();
    for (const body of bodies) {
        if (body !== null &&
            typeof body === 'object' &&
            typeof body.name === 'string' &&
            (body.name.toLowerCase() === target ||
                body.name.toLowerCase().includes(target))) {
            return body;
        }
    }
    return undefined;
}
exports.findReportByName = findReportByName;
function getReportNumericResult(body) {
    if (body === null || typeof body !== 'object')
        return undefined;
    const result = body.result;
    if (result === null || typeof result !== 'object')
        return undefined;
    const measures = result.measures;
    if (Array.isArray(measures)) {
        for (const measure of measures) {
            const data = measure?.data;
            if (typeof data === 'number' && Number.isFinite(data))
                return data;
        }
    }
    const instanceCount = result.instanceCount;
    if (typeof instanceCount === 'number' && Number.isFinite(instanceCount)) {
        return instanceCount;
    }
    return undefined;
}
exports.getReportNumericResult = getReportNumericResult;
function dashboardHasComparisonTile(definition) {
    if (definition === null || typeof definition !== 'object')
        return false;
    const tiles = definition.tiles;
    if (!Array.isArray(tiles))
        return false;
    return tiles.some((tile) => {
        const configuration = tile?.configuration;
        return (configuration !== null &&
            typeof configuration === 'object' &&
            configuration.comparisonPeriod === true);
    });
}
exports.dashboardHasComparisonTile = dashboardHasComparisonTile;
async function selectSingleProcessIfPossible(page) {
    const processFilter = page.getByPlaceholder(/all\s*processes/i).first();
    if (!(await processFilter.isVisible({ timeout: 10000 }).catch(() => false))) {
        return false;
    }
    await processFilter.click({ timeout: 15000 });
    const options = page.getByRole('option');
    await options
        .first()
        .waitFor({ state: 'visible', timeout: 10000 })
        .catch(() => { });
    const optionCount = await options.count();
    for (let i = 0; i < optionCount; i++) {
        const option = options.nth(i);
        const text = (await option.textContent())?.trim().toLowerCase() || '';
        if (text.length > 0 && !text.includes('all process')) {
            await option.click({ timeout: 10000 });
            return true;
        }
    }
    await page.keyboard.press('Escape').catch(() => { });
    return false;
}
exports.selectSingleProcessIfPossible = selectSingleProcessIfPossible;
