import { execSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { getPlaywriterProfileDir } from "../config/index.js";
import { logger } from "../logger.js";
const PLAYWRITER_EXTENSION_ID = "jfeammnjpkecdekppnclgkkffahnhfhe";
const PLAYWRITER_UPDATE_URL = "https://clients2.google.com/service/update2/crx";
function getChromeExternalExtensionsDir() {
    return join(homedir(), "Library", "Application Support", "Google", "Chrome", "External Extensions");
}
function getExpectedExtensionJson() {
    return JSON.stringify({ external_update_url: PLAYWRITER_UPDATE_URL }, null, 2);
}
function getExtensionJsonPath() {
    return join(getChromeExternalExtensionsDir(), `${PLAYWRITER_EXTENSION_ID}.json`);
}
function isExtensionJsonValid(jsonPath) {
    if (!existsSync(jsonPath))
        return false;
    try {
        const content = readFileSync(jsonPath, "utf-8");
        const parsed = JSON.parse(content);
        return parsed.external_update_url === PLAYWRITER_UPDATE_URL;
    }
    catch {
        return false;
    }
}
export function isPlaywriterExtensionJsonInstalled() {
    const systemPath = getExtensionJsonPath();
    const profilePath = join(getPlaywriterProfileDir(), "External Extensions", `${PLAYWRITER_EXTENSION_ID}.json`);
    return isExtensionJsonValid(systemPath) && isExtensionJsonValid(profilePath);
}
export function isPlaywriterPolicyConfigured() {
    if (process.platform !== "darwin")
        return false;
    try {
        const plistPath = "/Library/Managed Preferences/com.google.Chrome.plist";
        if (!existsSync(plistPath))
            return false;
        const content = execSync(`/usr/libexec/PlistBuddy -c "Print ExtensionInstallForcelist" "${plistPath}" 2>/dev/null`, { encoding: "utf-8", timeout: 5000 });
        return content.includes(PLAYWRITER_EXTENSION_ID);
    }
    catch {
        return false;
    }
}
export function isPlaywriterExtensionInChromeProfiles() {
    const chromeDataDir = join(homedir(), "Library", "Application Support", "Google", "Chrome");
    const profiles = [];
    try {
        if (existsSync(chromeDataDir)) {
            for (const entry of readdirSync(chromeDataDir)) {
                if (entry === "Default" || entry.startsWith("Profile ")) {
                    const extDir = join(chromeDataDir, entry, "Extensions", PLAYWRITER_EXTENSION_ID);
                    if (existsSync(extDir))
                        profiles.push(entry);
                }
            }
        }
    }
    catch {
        // Chrome data dir may not exist
    }
    return { installed: profiles.length > 0, profiles };
}
export function ensurePlaywriterExtension() {
    if (process.platform !== "darwin")
        return false;
    if (isPlaywriterPolicyConfigured()) {
        const cleanup = cleanupLegacyPlaywriterInstall();
        if (cleanup.policyRemoved) {
            logger.system(`Playwriter: legacy enterprise policy removed`);
        }
    }
    if (isPlaywriterExtensionJsonInstalled()) {
        return true;
    }
    try {
        const extJson = getExpectedExtensionJson();
        const systemExtDir = getChromeExternalExtensionsDir();
        mkdirSync(systemExtDir, { recursive: true });
        writeFileSync(getExtensionJsonPath(), extJson, "utf-8");
        logger.system("Playwriter: wrote External Extensions JSON to Chrome system path");
        const profileExtDir = join(getPlaywriterProfileDir(), "External Extensions");
        mkdirSync(profileExtDir, { recursive: true });
        writeFileSync(join(profileExtDir, `${PLAYWRITER_EXTENSION_ID}.json`), extJson, "utf-8");
        logger.system("Playwriter: wrote External Extensions JSON to dedicated profile");
        return true;
    }
    catch (err) {
        logger.system(`Playwriter: failed to write External Extensions JSON: ${err instanceof Error ? err.message : String(err)}`);
        return false;
    }
}
export function cleanupLegacyPlaywriterInstall() {
    const result = {
        policyRemoved: false,
        errors: [],
    };
    if (process.platform !== "darwin")
        return result;
    // 1. Remove enterprise policy entries
    if (isPlaywriterPolicyConfigured()) {
        try {
            scrubPlaywriterFromPolicyPlist("/Library/Managed Preferences/com.google.Chrome.plist");
            const username = (process.env.SUDO_USER ?? process.env.USER ?? "").trim()
                || execSync("id -un", { encoding: "utf-8" }).trim();
            if (username) {
                const userPlist = `/Library/Managed Preferences/${username}/com.google.Chrome.plist`;
                if (existsSync(userPlist)) {
                    scrubPlaywriterFromPolicyPlist(userPlist);
                }
            }
            try {
                execSync("sudo killall cfprefsd 2>/dev/null", { stdio: "pipe", timeout: 10_000 });
            }
            catch (err) {
                logger.system(`Playwriter: cfprefsd restart failed (not critical): ${err instanceof Error ? err.message : String(err)}`);
            }
            result.policyRemoved = true;
            logger.system("Playwriter: removed legacy enterprise policy");
        }
        catch (err) {
            result.errors.push(`Policy removal failed: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
    return result;
}
function scrubPlaywriterFromPolicyPlist(plistPath) {
    if (!existsSync(plistPath))
        return;
    try {
        const output = execSync(`/usr/libexec/PlistBuddy -c "Print ExtensionInstallForcelist" "${plistPath}" 2>/dev/null`, { encoding: "utf-8", timeout: 5000 });
        const lines = output.split("\n").filter((l) => l.trim().length > 0);
        const entries = [];
        for (const line of lines) {
            const trimmed = line.trim();
            if (trimmed !== "Array {" && trimmed !== "}") {
                entries.push(trimmed);
            }
        }
        const targetEntries = entries
            .map((e, i) => ({ entry: e, index: i }))
            .filter((e) => e.entry.includes(PLAYWRITER_EXTENSION_ID));
        if (targetEntries.length === 0)
            return;
        if (targetEntries.length === entries.length) {
            execSync(`sudo /usr/libexec/PlistBuddy -c "Delete ExtensionInstallForcelist" "${plistPath}"`, { stdio: "pipe", timeout: 10_000 });
        }
        else {
            for (let i = targetEntries.length - 1; i >= 0; i--) {
                execSync(`sudo /usr/libexec/PlistBuddy -c "Delete ExtensionInstallForcelist:${targetEntries[i].index}" "${plistPath}"`, { stdio: "pipe", timeout: 10_000 });
            }
        }
    }
    catch {
        // If ExtensionInstallForcelist doesn't exist, nothing to scrub
    }
}
export { PLAYWRITER_EXTENSION_ID };
//# sourceMappingURL=playwriter-extension.js.map