/**
 * MCP prompt that guides the LLM through the Playwright-based trace recording
 * and Skyramp test generation flow.
 */
import { z } from "zod";
import { logger } from "../utils/logger.js";
import { SKYRAMP_QA_PERSONA } from "../prompts/personas.js";
export function getTraceRecordingPromptText(opts) {
    const outputDir = opts?.outputDir;
    const modularize = opts?.modularize ?? true;
    const exportInstruction = outputDir
        ? `Call \`skyramp_export_zip\` with \`outputPath\` set to \`${outputDir}/<test_name>_trace.zip\` (absolute path).`
        : `Call \`skyramp_export_zip\` with \`outputPath\` set to the absolute zip path (same directory and base name as the test file, replacing \`.spec.ts\` with \`.zip\`).`;
    const generateInstruction = modularize
        ? `Call \`skyramp_ui_test_generation\` with \`playwrightInput\` set to the absolute zip path from the Export step.`
        : `Call \`skyramp_ui_test_generation\` with \`playwrightInput\` set to the absolute zip path from step 5 and \`modularizeCode: false\`.`;
    const modularizeNote = modularize
        ? `- **After generating the test**, run \`skyramp_modularization\` for code quality.`
        : `- Do NOT run \`skyramp_modularization\` — skip modularization in CI.`;
    return `## Skyramp UI Test Recording

${SKYRAMP_QA_PERSONA} For UI recording, every action must be grounded in what \`browser_snapshot\` returns. If an element is not visible in the snapshot, do not interact with it.

### Required workflow

Before starting, output a \`<thinking>\` block that maps each step of the user's intent to the specific browser interactions required. Do not call any tool until this mapping is complete.

Then execute in strict order:

1. **Navigate**: Call \`browser_navigate\` with the target URL. Always do this first, even if the browser appears to be on the correct page.
2. **Snapshot**: Call \`browser_snapshot\` to get the current ARIA tree and element refs.
3. **Interact**: Call the appropriate tool (\`browser_click\`, \`browser_type\`, \`browser_hover\`, etc.) using refs from the snapshot.
4. **Repeat steps 2–3** for each user action until all steps are complete.
5. **Export**: ${exportInstruction} Do NOT ask the user first — call it automatically.
6. **Generate**: ${generateInstruction}

### Cross-tool rules

- **After every action that changes the page**, call \`browser_snapshot\` before the next interaction — refs become stale after navigation, clicks that trigger page updates, and form submissions.
- **Iframe content** appears inline in the snapshot — interact with those elements using their refs normally.
- **Trace deduplication**: if you retry from the start URL, only the last complete attempt is exported.
- **No Docker required**: the \`browser_*\` tools run a local browser session managed by the MCP server. Docker is ONLY used by \`skyramp_start_trace_collection\` (manual recording mode). Never suggest or check for Docker when using AI-driven recording.
${modularizeNote}

### Tool discipline — three concepts, don't conflate

These concepts drive the DOM Analyzer capture tools (\`browser_sitemap_build\`, \`browser_sitemap_query\`, \`browser_blueprint\`) and constrain how their outputs flow into generated test code:

- **\`browser_snapshot\` — ephemeral refs**: the \`ref=e29\` values change on every call. Use them ONLY for dispatching the next 1–2 interactions (\`browser_click\`, \`browser_type\`, etc.). **Never put refs in generated test code** — they will not exist at playback time.
- **\`browser_blueprint\` — stable logical names**: logical names like \`add_order_btn\` and their derived \`getByRole\` locators survive page reloads and playback. Use them in generated test code. Call \`browser_blueprint\` only when the DOM has changed since the last known-good blueprint (modal opens, form submits, filter changes, mutable actions); for pure navigation to an already-crawled URL, reuse the Sitemap cache via \`browser_sitemap_query\`.
- **\`browser_sitemap_build\` — cached once per session**: crawls the whole app into a Sitemap. Call it once at the start of a session; subsequent calls within ~30 minutes reuse the cache unless \`refresh: true\` is passed. Read already-crawled pages via \`browser_sitemap_query\` (modes: \`page\`, \`edges\`, \`mapJson\`, \`outline\`) — do not re-call \`browser_sitemap_build\` to "check."

### Tool discipline — delta tools (consumers of captures)

These consume the outputs of the capture tools above; they don't capture state themselves.

- **\`browser_blueprint_diff\` — structured before/after delta**: takes two \`browser_blueprint\` results and returns \`elementsAdded\`, \`elementsRemoved\`, \`textChanges\`, \`repeatingCountChanges\`, \`urlChanged\`. Use it to derive assertions from observable state changes rather than guessing at what "success" looks like — capture before an action, perform the action, capture after, diff. An empty diff is itself a meaningful signal (e.g. a silent failure worth catching).
- **\`browser_widget_contract_lookup\` — custom widget interaction recipes**: when a blueprint element has \`widgetType: "custom"\` or \`"unknown"\`, look up its interaction recipe by \`fingerprint\` + \`ref\`. On \`"found"\`, the returned contract specifies the interaction steps (e.g. for a Radix Select: click trigger → wait for portal → click option). On \`"needs_inference"\`, fall through to snapshot-driven trial clicks. Use this so generated tests interact with custom widgets through stable contracts, not brittle positional clicks.

### Assertions
Call \`browser_assert\` when assertions are needed. Always provide the \`expected\` value.
- \`type: "text"\` — verify an element contains expected text
- \`type: "value"\` — verify an input field has an expected value

### Tips
- **Custom dropdowns (Radix, MUI, etc.)**: click the combobox trigger → \`browser_snapshot\` → click the option. Do NOT use \`browser_select_option\` — it only works on native \`<select>\` elements.

### Constraints
- Do NOT write JSONL or HAR files manually — \`skyramp_export_zip\` reads the recorded trace, builds the JSONL action log and HAR, and packages them into the zip.
- Do NOT reuse zip files from previous sessions — always record fresh.
`;
}
export function registerTraceRecordingPrompt(server) {
    logger.info("Registering trace recording prompt");
    server.registerPrompt("skyramp_trace_recording_prompt", {
        description: "Guide for recording browser interactions as a Skyramp trace and generating UI tests",
        argsSchema: {
            outputDir: z
                .string()
                .optional()
                .describe("Directory where zip files should be written. Defaults to same directory as the test file."),
            modularize: z
                .boolean()
                .default(true)
                .optional()
                .describe("Whether to run skyramp_modularization after generation. Default: true. Set to false in CI."),
        },
    }, (args) => ({
        messages: [
            {
                role: "user",
                content: {
                    type: "text",
                    text: getTraceRecordingPromptText({
                        outputDir: args.outputDir,
                        modularize: args.modularize,
                    }),
                },
            },
        ],
    }));
}
