import { ScreenshotItem } from "../screenshot-item.mjs";
import { uploadTestInfoToServer } from "../utils.mjs";
import { MIDSCENE_REPORT_QUIET, MIDSCENE_REPORT_TAG_NAME, globalConfigManager } from "@midscene/shared/env";
import { generateElementByRect } from "@midscene/shared/extractor";
import { getDebug } from "@midscene/shared/logger";
import { assert, logMsg, uuid } from "@midscene/shared/utils";
import dayjs from "dayjs";
import { debug } from "./task-cache.mjs";
const debugProfile = getDebug('web:tool:profile');
async function commonContextParser(interfaceInstance, _opt) {
    assert(interfaceInstance, 'interfaceInstance is required');
    debugProfile("Getting interface description");
    const description = interfaceInstance.describe?.() || '';
    debugProfile("Interface description end");
    debugProfile('Uploading test info to server');
    uploadTestInfoToServer({
        testUrl: description,
        serverUrl: _opt.uploadServerUrl
    });
    debugProfile('UploadTestInfoToServer end');
    const screenshotBase64 = await interfaceInstance.screenshotBase64();
    assert(screenshotBase64, 'screenshotBase64 is required');
    debugProfile('will get size');
    const size = await interfaceInstance.size();
    debugProfile(`size: ${size.width}x${size.height} dpr: ${size.dpr}`);
    const screenshot = ScreenshotItem.create(screenshotBase64);
    return {
        size,
        screenshot
    };
}
function getReportFileName(tag = 'web') {
    const reportTagName = globalConfigManager.getEnvConfigValue(MIDSCENE_REPORT_TAG_NAME);
    const dateTimeInFileName = dayjs().format('YYYY-MM-DD_HH-mm-ss');
    const uniqueId = uuid().substring(0, 8);
    return `${reportTagName || tag}-${dateTimeInFileName}-${uniqueId}`;
}
function printReportMsg(filepath) {
    if (globalConfigManager.getEnvConfigInBoolean(MIDSCENE_REPORT_QUIET)) return;
    logMsg(`Midscene - report file updated: ${filepath}`);
}
function getCurrentExecutionFile(trace) {
    const error = new Error();
    const stackTrace = trace || error.stack;
    const pkgDir = process.cwd() || '';
    if (stackTrace) {
        const stackLines = stackTrace.split('\n');
        for (const line of stackLines)if (line.includes('.spec.') || line.includes('.test.') || line.includes('.ts') || line.includes('.js')) {
            const match = line.match(/(?:at\s+)?(.*?\.(?:spec|test)\.[jt]s)/);
            if (match?.[1]) {
                const targetFileName = match[1].replace(pkgDir, '').trim().replace('at ', '');
                return targetFileName;
            }
        }
    }
    return false;
}
const testFileIndex = new Map();
function generateCacheId(fileName) {
    let taskFile = fileName || getCurrentExecutionFile();
    if (!taskFile) {
        taskFile = uuid();
        console.warn('Midscene - using random UUID for cache id. Cache may be invalid.');
    }
    if (testFileIndex.has(taskFile)) {
        const currentIndex = testFileIndex.get(taskFile);
        if (void 0 !== currentIndex) testFileIndex.set(taskFile, currentIndex + 1);
    } else testFileIndex.set(taskFile, 1);
    return `${taskFile}-${testFileIndex.get(taskFile)}`;
}
function ifPlanLocateParamIsBbox(planLocateParam) {
    return !!(planLocateParam.bbox && Array.isArray(planLocateParam.bbox) && 4 === planLocateParam.bbox.length);
}
function matchElementFromPlan(planLocateParam) {
    if (!planLocateParam) return;
    if (planLocateParam.bbox) {
        const rect = {
            left: planLocateParam.bbox[0],
            top: planLocateParam.bbox[1],
            width: planLocateParam.bbox[2] - planLocateParam.bbox[0] + 1,
            height: planLocateParam.bbox[3] - planLocateParam.bbox[1] + 1
        };
        const element = generateElementByRect(rect, 'string' == typeof planLocateParam.prompt ? planLocateParam.prompt : planLocateParam.prompt?.prompt || '');
        return element;
    }
}
async function matchElementFromCache(context, cacheEntry, cachePrompt, cacheable) {
    if (!cacheEntry) return;
    if (false === cacheable) return void debug('cache disabled for prompt: %s', cachePrompt);
    if (!context.taskCache?.isCacheResultUsed) return;
    if (!context.interfaceInstance.rectMatchesCacheFeature) return void debug('interface does not implement rectMatchesCacheFeature, skip cache');
    try {
        const rect = await context.interfaceInstance.rectMatchesCacheFeature(cacheEntry);
        const element = {
            center: [
                Math.round(rect.left + rect.width / 2),
                Math.round(rect.top + rect.height / 2)
            ],
            rect,
            description: 'string' == typeof cachePrompt ? cachePrompt : cachePrompt.prompt || ''
        };
        debug('cache hit, prompt: %s', cachePrompt);
        return element;
    } catch (error) {
        debug('rectMatchesCacheFeature error: %s', error);
        return;
    }
}
const getMidsceneVersion = ()=>"1.4.6";
const parsePrompt = (prompt)=>{
    if ('string' == typeof prompt) return {
        textPrompt: prompt,
        multimodalPrompt: void 0
    };
    return {
        textPrompt: prompt.prompt,
        multimodalPrompt: prompt.images ? {
            images: prompt.images,
            convertHttpImage2Base64: !!prompt.convertHttpImage2Base64
        } : void 0
    };
};
export { commonContextParser, generateCacheId, getCurrentExecutionFile, getMidsceneVersion, getReportFileName, ifPlanLocateParamIsBbox, matchElementFromCache, matchElementFromPlan, parsePrompt, printReportMsg };

//# sourceMappingURL=utils.mjs.map