"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    createRecorderMarkdownReplayPrompt: ()=>createRecorderMarkdownReplayPrompt,
    generateRecorderMarkdownReplay: ()=>generateRecorderMarkdownReplay,
    convertRecordLogIntoMarkdown: ()=>convertRecordLogIntoMarkdown
});
const recorder_namespaceObject = require("@midscene/shared/recorder");
const external_index_js_namespaceObject = require("../index.js");
const index_js_namespaceObject = require("../models/index.js");
const external_recorder_generation_common_js_namespaceObject = require("./recorder-generation-common.js");
function getMarkdownLanguageInstruction(language) {
    const normalizedLanguage = language?.trim();
    if (!normalizedLanguage) return '';
    return `
Language requirement:
- Write all human-readable Markdown instructions in ${normalizedLanguage}.
- Keep file paths, URLs, platform ids, API names, and quoted UI text unchanged.`;
}
function normalizeGeneratedMarkdown(content) {
    const trimmed = content.trim();
    const fencedMatch = trimmed.match(/^```(?:md|markdown)?\s*([\s\S]*?)\s*```$/i);
    return `${(fencedMatch?.[1] ?? trimmed).trim()}\n`;
}
function resolveModelRuntime(model) {
    if ('config' in model && 'adapter' in model) return model;
    return (0, index_js_namespaceObject.getModelRuntime)(model);
}
function createRecorderMarkdownReplayPrompt(input) {
    (0, external_recorder_generation_common_js_namespaceObject.validateEvents)(input.events);
    const { summary, screenshotAssets } = (0, external_recorder_generation_common_js_namespaceObject.prepareRecorderGenerationContext)(input);
    const promptText = `Generate a Markdown replay script for Midscene Agent.

This Markdown will be executed with:
await agent.runMarkdown('./x.md')

It is an AI-executable replay script, not a human report.

Target platform:
- Preserve this exact platform: ${input.target.platformId}
- Target block:
${(0, recorder_namespaceObject.stringifyMidsceneRecorderTargetBlock)(input.target)}

Replay goal:
- Reproduce the recorded user workflow exactly.
- Preserve event order.
- Preserve the user's original intent.
- Do not invent alternative navigation paths.
- Do not skip, merge, reorder, or add extra user actions.
- Prefer recorded UI text, element descriptions, URLs, input values, and scroll direction.
- Prefer event.replayInstruction and event.elementDescription when descriptionSource is "ai".
- If descriptionSource is "fallback", use the screenshot/context to write the best visual instruction.
- Coordinates are only fallback hints. Do not make coordinates the primary instruction when text or screenshots are available.
- If a target cannot be found, stop and report the missing step. Do not click similar-looking elements.
- Use screenshots only when they are provided below. Reference them by their exact relative paths.

Required Markdown structure:
# ${input.testName || summary.testName}

## Goal
Reproduce the recorded user workflow exactly.

## Target
- Platform: ${input.target.platformId}
- Start target: ${summary.startUrl || input.target.label || input.target.deviceId || 'Recorded target'}

## Replay rules
- Follow the steps in order.
- Do not invent alternative navigation paths.
- If a referenced target cannot be found, stop and report the missing step.

## Steps
1. ...

Event summary:
${JSON.stringify({
        ...summary,
        target: input.target,
        events: summary.events,
        screenshotAssets: screenshotAssets.map((asset)=>({
                eventIndex: asset.eventIndex,
                eventHashId: asset.eventHashId,
                eventType: asset.eventType,
                relativePath: asset.relativePath,
                description: (0, recorder_namespaceObject.getMidsceneRecorderEventDescription)(input.events[asset.eventIndex])
            }))
    }, null, 2)}

Screenshot rules:
- Insert a screenshot directly under the step that needs visual grounding.
- Use Markdown image syntax exactly like: ![step context](./screenshots/event-001-click.png)
- Only reference paths listed in screenshotAssets.
- Do not reference images that are not listed.${getMarkdownLanguageInstruction(input.language)}

Important: Return ONLY raw Markdown. Do NOT wrap the response in markdown code blocks.`;
    const content = [
        {
            type: 'text',
            text: promptText
        }
    ];
    for (const asset of screenshotAssets){
        content.push({
            type: 'text',
            text: `Screenshot asset for event #${asset.eventIndex + 1}: ${asset.relativePath}`
        });
        content.push({
            type: 'image_url',
            image_url: {
                url: asset.dataUrl
            }
        });
    }
    return [
        {
            role: 'system',
            content: "You generate precise Markdown replay scripts for Midscene agent.runMarkdown. The output must be deterministic, ordered, and safe for AI execution."
        },
        {
            role: 'user',
            content
        }
    ];
}
async function generateRecorderMarkdownReplay(input, model) {
    try {
        const prompt = createRecorderMarkdownReplayPrompt(input);
        const response = await (0, external_index_js_namespaceObject.callAIWithStringResponse)(prompt, resolveModelRuntime(model));
        if (response?.content && 'string' == typeof response.content) return normalizeGeneratedMarkdown(response.content);
        throw new Error('Failed to generate recorder Markdown replay');
    } catch (error) {
        throw new Error(`Failed to generate recorder Markdown replay: ${error}`);
    }
}
async function convertRecordLogIntoMarkdown(log, modelConfig) {
    return generateRecorderMarkdownReplay(log, modelConfig);
}
exports.convertRecordLogIntoMarkdown = __webpack_exports__.convertRecordLogIntoMarkdown;
exports.createRecorderMarkdownReplayPrompt = __webpack_exports__.createRecorderMarkdownReplayPrompt;
exports.generateRecorderMarkdownReplay = __webpack_exports__.generateRecorderMarkdownReplay;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "convertRecordLogIntoMarkdown",
    "createRecorderMarkdownReplayPrompt",
    "generateRecorderMarkdownReplay"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});

//# sourceMappingURL=markdown-generator.js.map