import { getPersonaPrefix } from "../personas.js";
import { maintenanceTaskSuffix, renderRule, } from "./sharedAssertionRules.js";
const UI_ASSERTION_CATEGORIES = [
    {
        name: "Critical UI Assertions",
        rules: [
            {
                title: "Selector constraints",
                description: "Every assertion uses a selector already in the file. Never invent `data-testid`, role names, or classes.",
                subPoints: [
                    "No tautological assertions — locating an element by text X, then asserting it contains X.",
                ],
                examples: [
                    {
                        language: "javascript",
                        code: `await expect(page.getByTestId('badge-count')).toHaveText('3');`,
                    },
                ],
            },
            {
                title: "Page errors",
                description: "Register `page.on('pageerror', ...)` before the first navigation and assert `expect(errors).toHaveLength(0)` at the end of the test.",
                examples: [],
            },
            {
                title: "Correct intended behavior",
                description: "Assertions encode the expected outcome of the action, not the buggy runtime output observed in the trace.",
                examples: [
                    {
                        language: "javascript",
                        code: `await expect(page.locator('[data-testid="session-row"]')).toHaveCount(3);`,
                    },
                ],
            },
            {
                title: "Tests target the changed behavior introduced by the pull request",
                description: "At least one assertion targets the changed behavior on populated or updated state, not only empty or zero state.",
                examples: [],
            },
            {
                title: "Collection / repeated UI elements",
                description: "For every collection page or selector matching multiple rendered nodes (items, rows, cards, badges, tabs, chips, definition rows, nav items), assert the exact count plus per-item content.",
                subPoints: [
                    "Use `toHaveCount(N)` where N comes from the trace array length or rendered DOM (`0` for empty state).",
                    "Add at least one concrete per-item content assertion (`toHaveText`, `toHaveValue`, `toHaveAttribute`).",
                    "Empty trace → `toHaveCount(0)` paired with the empty-state text.",
                ],
                examples: [
                    {
                        language: "javascript",
                        code: `await expect(page.getByRole('row')).toHaveCount(2);
await expect(page.getByRole('cell', { name: 'admin@example.com' })).toHaveText('admin@example.com');`,
                    },
                    {
                        language: "javascript",
                        code: `await expect(page.getByTestId('notification-badge')).toHaveText('3');
await expect(page.getByTestId('notification-row')).toHaveCount(3);`,
                    },
                    {
                        language: "javascript",
                        code: `await expect(page.getByTestId('definition-row')).toHaveCount(3);
await expect(page.getByTestId('definition-row').nth(0)).toHaveText('Version 10.2.1');`,
                    },
                ],
            },
            {
                title: "Positive-path companion",
                description: "Negative-only checks and URL-only routing tests must include at least one positive rendered-element assertion such as a heading, breadcrumb, title, link, count, or exact text.",
                examples: [
                    {
                        language: "javascript",
                        code: `await expect(page).toHaveURL(/\\/users/);
await expect(page.getByRole('heading')).toHaveText('User Directory');`,
                    },
                ],
            },
            {
                title: "Captured network responses",
                description: "For every `page.waitForResponse`, `page.on`, or `page.route`, assert at least one status, body, or header field. Body values used downstream must also appear as visible UI text.",
                examples: [
                    {
                        language: "javascript",
                        code: `const loginResp = await page.waitForResponse('**/login');
expect(loginResp.status()).toBe(200);
expect((await loginResp.json()).user.email).toBe('admin@example.com');`,
                    },
                ],
            },
        ],
    },
    {
        name: "Computed Values",
        rules: [
            {
                title: "Exact rendered values",
                description: "When the exact text, value, or attribute is knowable from the trace or source, use `toHaveText`, `toHaveValue`, or `toHaveAttribute` — never `toBeVisible` or `toContainText`.",
                subPoints: [
                    "Definition / info pages: assert the actual displayed values (version, count, date), not just the static label text.",
                    "Images: assert `toHaveAttribute('src', ...)` with the exact src — never visibility alone.",
                ],
                examples: [
                    {
                        language: "javascript",
                        code: `await expect(page.getByTestId('status')).toHaveText('Active');`,
                    },
                    {
                        language: "javascript",
                        code: `await expect(page.getByTestId('product-image')).toHaveAttribute('src', /expected-pattern/);`,
                    },
                ],
            },
        ],
    },
    {
        name: "Post-edit State",
        description: "Apply only when the test contains a state-changing action. Otherwise mark NOT APPLICABLE.",
        rules: [
            {
                title: "Post-action visible state",
                description: "After a state-changing action (form fill+submit, save / delete / create / toggle, checkbox click, hover / mouseout, refresh, reload, JS update, form edit), assert the visible updated outcome via `toHaveText`, `toHaveValue`, `toHaveAttribute`, or `toBeChecked`. The displayed values must reflect the edit.",
                subPoints: [
                    "Toggle / checkbox renames: assert the new label or state, not `toBeVisible` on the renamed element.",
                    "Hover / mouseout: assert the overlay or state visible / hidden after the event.",
                    "List edit: when the test submits N items, assert exactly N rows. When the count is unknown before the action, read it before and assert the delta after.",
                ],
                examples: [
                    {
                        language: "javascript",
                        code: `await expect(page.getByTestId('description-checkbox')).toBeChecked();
await expect(page.getByTestId('description-label')).toHaveText('check_box Description');`,
                    },
                    {
                        language: "javascript",
                        code: `await expect(page.getByTestId('total')).toHaveText('$19.98');`,
                    },
                    {
                        language: "javascript",
                        code: `await expect(page.getByTestId('version')).toHaveText('10.2.1');`,
                    },
                ],
            },
        ],
    },
];
function renderCategories(categories) {
    let index = 0;
    return categories
        .map((category) => {
        const rendered = category.rules
            .map((rule) => {
            index += 1;
            return renderRule(index, rule);
        })
            .join("\n\n");
        const header = `#### ${category.name}`;
        return category.description
            ? `${header}\n${category.description}\n\n${rendered}`
            : `${header}\n${rendered}`;
    })
        .join("\n\n");
}
function renderAssertionCategoriesTemplate(categories) {
    return categories
        .map((category) => {
        const ruleKeys = category.rules
            .map((rule) => `      "${rule.title}": []`)
            .join(",\n");
        return `    "${category.name}": {\n${ruleKeys}\n    }`;
    })
        .join(",\n");
}
export function getUIAssertionsPrompt(testFile, enhanceType) {
    const categoryTemplate = renderAssertionCategoriesTemplate(UI_ASSERTION_CATEGORIES);
    return `${getPersonaPrefix()}Your task is to enhance assertions for the given UI test file: \`${testFile}\`.${maintenanceTaskSuffix(enhanceType)}

### First Check
If the generated test file has no \`expect()\` assertions, you MUST manually add them before anything else. Use \`import { expect } from '@skyramp/skyramp';\` — never from \`@playwright/test\`. If an existing import pulls \`expect\` from \`@playwright/test\`, move it to \`@skyramp/skyramp\` (keep \`test\` on the playwright line).

### Pre-Edit Assertion Analysis
Before editing the given test file, you must output a \`<thinking>\` block. The aim of the \`<thinking>\` block is to analyze each in-scope item (action, selector, or captured network response) in the given test file and output a JSON array that ensures no assertion rule is overlooked. The JSON array should match the template below — every assertion category and every rule title under it must appear as a key, even when the value is \`[]\`.
1. Selector inventory — list every selector already present in the generated test file (\`data-testid\`, role + name, text, label, etc.). New assertions may use only selectors from this list. Do not invent \`data-testid\` values, role names, or aria attributes. Also note captured network responses, repeated element patterns, exact rendered text/value/attribute from trace/source, and existing \`toBeVisible()\` assertions whose exact text is knowable.
2. Process — Replay → Identify → Fix or Add — walk through these three steps explicitly.
   a. Replay the scenario mentally. At each state-changing action (form submit, item add/edit/delete), ask: "What is the EXPECTED outcome based on the action performed?"
   b. Identify expectation mismatches. If the recorded trace shows a result that contradicts the action (e.g. removing 1 of 2 items but the page shows 3, submitting a form but getting a blank page, editing a field but the old value persists), that is an app bug the test should catch. List every mismatch you find.
   c. Fix or add assertions for each mismatch.
      - If an existing assertion uses the wrong (buggy) value, edit it to assert the correct expected value.
      - If no assertion exists for the buggy behavior, add one immediately after the action that triggers it.
3. Classify each in-scope action / selector / captured response by its applicable assertion category, marking each category APPLICABLE or NOT APPLICABLE.
   - Critical UI Assertions applies when there is a collection / repeated element (\`toHaveCount\`), a pageerror handler, a captured network response, a negative-only or URL-only test needing a positive-path companion, or a tautological locator-by-text + assert-text to replace.
   - Computed Values applies when there is a knowable exact text / value / attribute, including a definition-page displayed value or an image \`src\`.
   - Post-edit State applies only when the test contains a state-changing action (form fill+submit, save / delete / create / toggle, checkbox click, hover / mouseout, refresh, reload, JS update, form edit); otherwise NOT APPLICABLE.
4. For each in-scope item, output one JSON object using the template below. The output is an array — repeat the object template below once per in-scope item.
   - \`action_or_selector_or_response\`: the selector, action, or captured network response this entry covers.
   - \`assertion_categories\`: an object that MUST contain every category name below as a key. The value of each category is itself an object that MUST contain every rule title under that category as a key. For each rule, the value is an array of assertion lines you will add for this item under that rule. Use \`[]\` only when the rule does not apply to this item — every category key and every rule key must still be present. This forces you to consider every rule for every item.

\`\`\`json
[{
  "action_or_selector_or_response": "<selector | action | response>",
  "assertion_categories": {
${categoryTemplate}
  }
}]
\`\`\`

### Assertion Rules with Examples
Most-violated patterns — apply every time. (1) repeated elements → \`toHaveCount(N)\` + per-item \`toHaveText\`/\`toHaveValue\`/\`toHaveAttribute\` (Collection / repeated UI elements). (2) post-action state → \`toHaveText\`/\`toHaveValue\`/\`toHaveAttribute\`/\`toBeChecked\`, not \`toBeVisible\` when exact value is knowable (Post-action visible state). (3) routing/URL-only tests → at least one rendered-element exact text (Positive-path companion).
Strength order. \`toHaveCount\`/\`toHaveText\`/\`toHaveValue\`/\`toHaveAttribute\` > \`toContainText\` (only when string is genuinely dynamic) > \`toBeVisible\` (only when presence is the actual test).

${renderCategories(UI_ASSERTION_CATEGORIES)}

### What Not to Do
- Do not invent selectors, values, attributes, or assertions
- Do not use \`toBeVisible\` when exact text/value/state is knowable
- Do not use tautological locator-by-text + assert-text
- Do not use \`toContainText\` when the full string is known
- Do not assert static page headings, intermediate states, or values guaranteed by the action you just took
- Do not assert the same value with multiple selectors
- Do not import \`expect\` from \`@playwright/test\`
- Do not restructure, reorder, or modify existing code/imports/signatures
- Do not add comments or docstrings
- Do not remove or modify existing assertions
- Do not assert buggy/error text as expected (unless the intended UX is an error state)

### Verification of Assertions
After adding all assertion lines in the given test file, verify that every applicable rule has been applied correctly to each in-scope action, selector, and captured response. If any are missing or weakly applied, fix them before completing.

The goal is tests that FAIL when the app has bugs, not tests that simply replay what happened.
`;
}
