import { generateSkyrampHeader, SKYRAMP_UTILS_HEADER } from "../utils/utils.js";
import { getPomAwareCodeReusePrompt } from "./pom-aware-code-reuse.js";
const LANGUAGE_MAP = {
    python: {
        extension: "py",
        fileName: "SkyrampUtils.py",
    },
    java: {
        extension: "java",
        fileName: "SkyrampUtils.java",
    },
    javascript: {
        extension: "js",
        fileName: "skyrampUtils.js",
    },
    typescript: {
        extension: "ts",
        fileName: "skyrampUtils.ts",
    },
};
export function getCodeReusePrompt(testFile, language, framework) {
    const isTypescriptPlaywright = language.toLowerCase() === "typescript" &&
        framework?.toLowerCase() === "playwright";
    if (isTypescriptPlaywright) {
        return getPomAwareCodeReusePrompt(testFile);
    }
    const ext = LANGUAGE_MAP[language].extension || "py";
    const fileName = LANGUAGE_MAP[language].fileName || "SkyrampUtils.py";
    const codegenMarker = `${ext === "py" ? "#" : "//"} Generated by Skyramp v`;
    return `# CODE REUSE - 6 CLEAR STEPS 
**CRITICAL WARNING: VIOLATION OF THESE RULES WILL RESULT IN ERROR**

## DEFINITIONS (READ FIRST):
**What is a "Helper Function"?**
- A helper function is a STANDALONE, DISTINCT function that is ALREADY DEFINED in the code
- It has a clear function signature (e.g., \`async function createProduct(page, data) { ... }\`)
- It is NOT just repetitive inline test code or patterns
- Example of helper function: \`async function loginUser(page, email, password) { ... }\`
- Example of NOT a helper function: Repetitive \`await page.click()\` statements scattered in test

**What is "Repetitive Code Pattern"?**
- Sequential test steps that look similar but are NOT extracted into standalone functions
- Example: Multiple sequences of \`await page.fill()\`, \`await page.click()\` directly in test body
- These patterns should NOT be extracted during code reuse - that's what modularization is for

** CODE REUSE ≠ REFACTORING**
- Code reuse = Finding EXISTING helper functions and reusing them
- Refactoring = Creating NEW helper functions from patterns (handled by modularization tool)

## STEP 1: READ TEST FILE
Read ${testFile} and look for ALREADY DEFINED helper functions (not just repetitive patterns).

## STEP 2: FIND EXISTING UTILS
Use the Grep tool to search for files containing "${SKYRAMP_UTILS_HEADER}":
- Pattern: "${SKYRAMP_UTILS_HEADER}"
- Type: "${ext}"
- Output mode: "files_with_matches"
**CRITICAL: Only look for util files with header ${SKYRAMP_UTILS_HEADER}** - exclude test files (files with "test", "spec", ".test.", ".spec." in the name).
Read the matching non-test files and check if any helpers can be reused in ${testFile}.

## STEP 3: USE EXISTING HELPERS FROM UTILS SOURCE FILES FOUND IN STEP 2
If helpers exist in util file that can be reused in ${testFile} without modifying them:
- Import them into ${testFile}
- Remove any duplicate code in ${testFile}
- Test that ${testFile} still works without any errors and logical is same as original test file.

## STEP 4: FIND LOCAL HELPERS IN OTHER SKYRAMP-GENERATED TEST FILES

You are looking for sibling test files generated by Skyramp's codegen. They start with the comment line \`${codegenMarker}…\` (note: the version suffix is what distinguishes them from the SkyrampUtils header). The substring \`${SKYRAMP_UTILS_HEADER}\` is contained in that line, so:

Use the Grep tool to search for other test files containing "${SKYRAMP_UTILS_HEADER}":
- Pattern: "${SKYRAMP_UTILS_HEADER}"
- Type: "${ext}"
- Output mode: "files_with_matches"

**CRITICAL: Exclude ${testFile} from the results** — only look at OTHER files, not the current file.

The result will mix two kinds of files:
- **Utils file(s)** — already handled by STEP 2/STEP 3.
- **Other Skyramp-generated test files** — these are the targets of STEP 4 / 4b / 5. Identify them by the \`${codegenMarker}\` codegen marker on line 1 (NOT the bare utils header).

**STOP HERE IF NO OTHER SKYRAMP-GENERATED TEST FILES FOUND**
**IF NO OTHER SKYRAMP-GENERATED TEST FILES ARE FOUND, SKIP TO STEP 6 - DO NOT CREATE ANY UTILS FILES.**

If other Skyramp-generated test files are found, read those files and look for ALREADY DEFINED helper functions with clear function signatures.

**How to identify helper functions in other test files:**
 HELPER FUNCTION (move to utils):
   - Has function signature: \`async function doSomething(params) { ... }\`
   - Can be called multiple times with different parameters
   - Example: \`async function fillProductForm(page, product) { ... }\`

NOT A HELPER FUNCTION (do not extract):
   - Just repetitive inline test code in test body
   - No function definition/signature
   - Example: Multiple \`await page.getByTestId("xyz").click()\` directly in test

**IF OTHER TEST FILES ONLY CONTAIN REPETITIVE PATTERNS (NO ACTUAL HELPER FUNCTIONS), SKIP TO STEP 6**
**IF OTHER SKYRAMP-GENERATED TEST FILES ARE BYTE-FOR-BYTE IDENTICAL TO ${testFile}, SKIP TO STEP 6** (note: helpers being NEAR-duplicates does NOT count as identical — proceed to STEP 4b)

## STEP 4b: PARAMETERIZE NEAR-DUPLICATE HELPERS ACROSS SKYRAMP-GENERATED TEST FILES

**This step handles the cross-test case: ${testFile} AND another Skyramp-generated test file each define their own helper that does the SAME shape of work with only literal-value differences. These should become ONE parameterized helper in \`${fileName}\`.**

### Definition: "near-duplicate" helpers

Two helpers (one in ${testFile}, one in another Skyramp-generated test file found in STEP 4) are near-duplicates when **ALL** of the following are true:

1. **Same Playwright primitive sequence** — they call the same Playwright APIs in the same order (e.g. both: \`getByText(...).click()\` → \`waitForEvent("filechooser")\` → \`fileChooser.setFiles(...)\` → \`waitForResponse(...)\`).
2. **Differences are limited to literal values** — selectors, role names, test IDs, URL patterns, button labels, or other string/number literals. NO structural difference (no extra step in one and not the other, no different control flow, no extra arguments that change behavior).
3. **The differing literals are trivially liftable to parameters** — no logic needs to be invented to derive them.

If any of the three is false → NOT near-duplicates. Leave them alone.

### Worked example

\`flow-1.spec.ts\` has:
\`\`\`ts
export async function upload_translation_file(page, fileName) {
    await page.waitForTimeout(1500);
    const responsePromise1 = page.waitForResponse("**/api/files/upload**");
    const fileUploadPromise0 = page.waitForEvent("filechooser");
    await page.getByText("Choose a file").first().click();
    const fileChooser0 = await fileUploadPromise0;
    await fileChooser0.setFiles(fileName);
    const response1 = await responsePromise1;
    await page.waitForTimeout(1500);
}
\`\`\`

\`${testFile}\` (current) has:
\`\`\`ts
export async function uploadFileToRFI(page, fileName, tabName) {
    await page.waitForTimeout(1500);
    const responsePromise1 = page.waitForResponse("**/api/files/upload**");
    const fileUploadPromise0 = page.waitForEvent("filechooser");
    await page.getByText("Choose a file").click();
    const fileChooser0 = await fileUploadPromise0;
    await fileChooser0.setFiles(fileName);
    const response1 = await responsePromise1;
    await page.waitForTimeout(1500);
}
\`\`\`

These ARE near-duplicates. Same primitive sequence; the only material difference is the \`.first()\` qualifier on the locator. \`tabName\` is unused in the body — recorder noise, drop it. Correct merge:

\`\`\`ts
export async function uploadFileViaChooser(page, fileName) {
    await page.waitForTimeout(1500);
    const responsePromise = page.waitForResponse("**/api/files/upload**");
    const fileUploadPromise = page.waitForEvent("filechooser");
    await page.getByText("Choose a file").first().click();
    const fileChooser = await fileUploadPromise;
    await fileChooser.setFiles(fileName);
    await responsePromise;
    await page.waitForTimeout(1500);
}
\`\`\`

Both test files import and call \`uploadFileViaChooser(page, fileName)\`.

### Procedure

For each helper defined locally in ${testFile}:

1. **Scan** each OTHER Skyramp-generated test file from STEP 4 for a helper that matches the near-duplicate criteria above.
2. **If no match** → skip this helper, move on.
3. **If exactly one match** → parameterize and merge:
   - **Name**: pick a name describing INTENT, not the originating test. E.g. \`uploadFileViaChooser\`, not \`upload_translation_file\` or \`uploadFileToRFI\`.
   - **Parameters**: the literal values that differ across the two call sites. Drop any parameter that is unused in the body (recorder noise).
   - **Body**: the common primitive sequence with the differing literals replaced by parameters.
   - **Forbidden**: do NOT add if/else, ternaries, defaults, or any logic to bridge the differences. If a single body can't cover both call sites without new logic, they are NOT near-duplicates — leave them alone.
4. **If multiple matches** → process each pair independently. Merge every pair that clearly meets all three near-duplicate criteria. Skip any pair you're uncertain about — a missed merge is recoverable, a wrong merge breaks both tests.
5. **Write** the merged helper into \`${fileName}\` (create the file with the standard header if it doesn't exist; same header as STEP 5 below).
6. **Delete** both original helpers from their test files.
7. **Import** the merged helper from \`${fileName}\` into both test files.
8. **Replace** the two original call sites with calls to the merged helper, passing the values that were originally hardcoded or argument-passed in each test.

### Hard rules

- **Conservative bias**: a wrong merge breaks both tests; a missed merge leaves a duplicate. When in doubt, do NOT merge.
- **No "cleanup"**: the merged body must mirror the original primitive sequence — same waits, same correlation patterns, same order. This is not refactoring.
- **Preserve typing style**: if originals used \`page: any\` (or untyped \`page\`), keep that convention.
- **Don't merge with helpers already in \`${fileName}\`**: those are STEP 3's territory. STEP 4b is strictly cross-test merge between sibling Skyramp-generated test files.

---

## STEP 5: IF LOCAL HELPERS ARE FOUND IN STEP 4 THAT CAN BE REUSED in ${testFile}, MOVE THOSE LOCAL HELPERS TO UTILS SOURCE FILES AND USE THEM

**This step covers the EXACT-DUPLICATE / move-as-is case. STEP 4b already handled the near-duplicate case — do NOT re-process helpers that STEP 4b already merged.**

**ONLY PROCEED WITH STEP 5 IF ALL CONDITIONS ARE MET:**
- You found OTHER test files in STEP 4 (not just ${testFile})
- Those test files contain ACTUAL HELPER FUNCTIONS with function signatures (not just repetitive patterns)
- The helper functions are ALREADY IMPLEMENTED and working in those OTHER test files
- The helper in the OTHER test file is byte-for-byte usable in ${testFile} without any modification — if a helper would need parameterizing to fit both call sites, it is a near-duplicate and STEP 4b owns it; do NOT process those helpers here

**IF ANY CONDITION IS NOT MET, SKIP TO STEP 6 - DO NOT CREATE ANY UTILS FILES.**

**Examples of when to SKIP STEP 5:**
- Other test files have identical repetitive code but no helper functions
- Other test files are generated from same template and look identical
- You see patterns but no actual function definitions
- You would need to CREATE new functions to extract the patterns

**CRITICAL:** For helpers found in STEP 4:
1. **CREATE** \`${fileName}\` file if it doesn't exist with the following header:
   \`\`\`${ext}
   ${generateSkyrampHeader(language)}
   \`\`\`
**CRITICAL: IF \`${fileName}\` is already big, create a new file with a different name and add the header to the new file.**
2. **COPY** those local helper functions from original test source files to \`${fileName}\` without modifying them
3. **DELETE** those local helper functions from test source files (REMOVE THEM COMPLETELY) WITHOUT ANY OTHER CHANGES.
4. **IMPORT** those local helper functions from \`${fileName}\` back into test source files WITHOUT MAKING ANY OTHER CHANGE.
5. **IMPORT** those local helper functions from \`${fileName}\` into ${testFile}
6. **REPLACE** duplicate code in ${testFile} with calls to imported helper functions WITHOUT MAKING ANY OTHER CHANGE.

**CRITICAL: DO NOT CREATE UNNECESSARY HELPER FUNCTIONS** 
**DO NOT CREATE HELPERS BASED ON PATTERNS IN THE CURRENT FILE** 

## STEP 6: VERIFY AND VALIDATE
1. **BEFORE** making any changes, read the original test file and identify ALL helper functions
2. **AFTER** copying helpers to utils, read the original file again to confirm helpers are GONE
3. **VERIFY** that helper functions are NO LONGER in original test files
4. **VERIFY** that the original test files only have import statements and no duplicate code
5. **VERIFY** that both original and new test files import from utils and use the helper functions
5a. **VERIFY STEP 4b OUTCOMES** — for every near-duplicate pair you merged in STEP 4b: the merged helper exists in \`${fileName}\` exactly once; BOTH original helpers are deleted from their respective test files; BOTH test files import the merged helper from \`${fileName}\`; BOTH original call sites are replaced with calls to the merged helper. If any of these is false, fix it before finishing.
6. **VERIFY** that no unnecessary helper functions were created (functions that duplicate existing functionality)
7. **VERIFY** that all helper functions in utils are actually imported and used in the test files
8. **REMOVE** any helper functions that are not being used after refactoring
9. **NEVER** refactor, reorganize, or restructure existing source test files beyond moving helpers
10. **RUN TESTS** to ensure functionality is preserved after refactoring

**FINAL REMINDER: DO NOT CREATE HELPER FUNCTIONS FROM SCRATCH** 
**ONLY MOVE EXISTING HELPERS FROM OTHER TEST FILES** 

**IMPORTANT NOTES:**
- The process is designed to REUSE existing helper functions, not create new ones
- If no existing helpers are found, the test file should remain unchanged
- Code reuse is about moving existing, working helper functions between files
- Never create helper functions based on patterns you see in the current test file
- Helper functions must have explicit function signatures/definitions
- Repetitive inline test code is NOT a helper function

**DECISION TREE:**
1. Found existing utils file with helpers? → Import and use them (Step 3)
2. Found other test files with ACTUAL helper functions? → Move to utils (Step 5)
3. Found other test files with only repetitive patterns? → SKIP to Step 6, NO utils file
4. Found no other test files? → SKIP to Step 6, NO utils file
5. Other test files identical to current? → SKIP to Step 6, NO utils file

**MANDATORY**: After code reuse is complete, proceed to modularization by calling skyramp_modularization tool ONLY for UI, E2E, INTEGRATION or LOAD test types generated from traces.

SUMMARIZE THE CODE REUSE PROCESS AND THE RESULTS.
`;
}
