import fs from "fs";
import { logger } from "./logger.js";
const PLAYWRIGHT_IMPORT_RE = /import\s*\{([^}]*)\}\s*from\s*['"]@playwright\/test['"]\s*;?[ \t]*\r?\n?/g;
const SKYRAMP_IMPORT_RE = /import\s*\{([^}]*)\}\s*from\s*['"]@skyramp\/skyramp['"]\s*;?/;
const EXPECT_USAGE_RE = /\bexpect\s*\(/;
const LAST_IMPORT_RE = /^import\s[^;]*;[ \t]*$/gm;
function splitImports(raw) {
    return raw
        .split(",")
        .map((s) => s.trim())
        .filter(Boolean);
}
/**
 * Ensure `expect` is imported from `@skyramp/skyramp` rather than `@playwright/test`.
 * - Strips `expect` from any `@playwright/test` import (keeps other identifiers).
 * - If the file uses `expect(...)`, ensures an `@skyramp/skyramp` import carries `expect`.
 * Returns the original string if no rewrite was needed.
 */
export function normalizeSkyrampExpectImport(source) {
    let out = source;
    out = out.replace(PLAYWRIGHT_IMPORT_RE, (match, raw) => {
        const items = splitImports(raw);
        const idx = items.findIndex((item) => item === "expect");
        if (idx === -1)
            return match;
        items.splice(idx, 1);
        if (items.length === 0)
            return "";
        return `import { ${items.join(", ")} } from '@playwright/test';\n`;
    });
    if (!EXPECT_USAGE_RE.test(out))
        return out;
    const skyrampMatch = out.match(SKYRAMP_IMPORT_RE);
    if (skyrampMatch) {
        const items = splitImports(skyrampMatch[1]);
        if (items.includes("expect"))
            return out;
        items.push("expect");
        out = out.replace(SKYRAMP_IMPORT_RE, `import { ${items.join(", ")} } from '@skyramp/skyramp';`);
        return out;
    }
    const newImport = `import { expect } from '@skyramp/skyramp';`;
    const imports = [...out.matchAll(LAST_IMPORT_RE)];
    const last = imports[imports.length - 1];
    if (last && last.index !== undefined) {
        const insertAt = last.index + last[0].length;
        return out.slice(0, insertAt) + "\n" + newImport + out.slice(insertAt);
    }
    return newImport + "\n" + out;
}
/**
 * Normalize the `expect` import in a file on disk. No-op if the file is missing,
 * unreadable, or already correct. Errors are swallowed — this is a safety net,
 * not a blocking step.
 */
export function normalizeSkyrampImportsInFile(testFile) {
    if (!testFile)
        return;
    try {
        if (!fs.existsSync(testFile))
            return;
        const src = fs.readFileSync(testFile, "utf8");
        const fixed = normalizeSkyrampExpectImport(src);
        if (fixed !== src) {
            fs.writeFileSync(testFile, fixed);
            logger.info("Normalized @skyramp/skyramp expect import", { testFile });
        }
    }
    catch (err) {
        logger.warning("Failed to normalize skyramp imports", {
            testFile,
            error: err.message,
        });
    }
}
