// ============================================================================
// PDB Garment Picker Launcher
//
// Gates the PDB picker (Ctrl+Alt+P) behind ProofLab license check.
// Loads security, validates license, then opens picker URL in default browser.
//
// Developed by: Martin Castellanos
// Maintained by: GXS Operations Team
// Copyright: (c) Graph X Source. All Rights Reserved.
// License: Proprietary & Confidential.
// ============================================================================

(function () {
    var scriptFile = new File($.fileName);
    var scriptDir = scriptFile.parent;
    var scriptDirPath = scriptDir.fsName.replace(/\\/g, "/");

    var modules = [
        "lib/00_logger",
        "lib/06_versioning",
        "lib/01_json_polyfill",
        "lib/i18n/en_us",
        "lib/i18n/es_hn",
        "lib/07_i18n",
        "lib/05_security",
        "lib/02_settings"
    ];

    var isProduction = true;
    for (var i = 0; i < modules.length; i++) {
        var moduleBin = new File(scriptDirPath + "/" + modules[i] + ".jsxbin");
        var moduleJsx = new File(scriptDirPath + "/" + modules[i] + ".jsx");
        var moduleFile = null;
        if (moduleBin.exists) {
            moduleFile = moduleBin;
        } else if (moduleJsx.exists) {
            moduleFile = moduleJsx;
            isProduction = false;
        } else {
            alert("Error: Required module not found.\n\nMissing: " + modules[i]);
            return;
        }
        try {
            $.evalFile(moduleFile);
        } catch (e) {
            alert("Error loading module: " + modules[i] + "\n\n" + e.toString());
            return;
        }
    }

    $.global.PRLB_PRODUCTION = isProduction;

    var securityResult = security.check();
    if (!securityResult.ok) {
        security.showActivationError(securityResult.machineID);
        if (typeof prlbLogger !== "undefined") {
            prlbLogger.log("SECURITY", "WARN", "Access denied (PDB Picker) - Machine ID: " + securityResult.machineID);
        }
        return;
    }
    if (typeof prlbLogger !== "undefined") {
        prlbLogger.log("SECURITY", "INFO", "License check passed (PDB Picker)");
    }

    var pickerUrl = "http://127.0.0.1:4311/picker/";
    try {
        var rootDir = scriptDir.parent;
        if (rootDir && rootDir.exists) {
            var configFile = new File(rootDir.fsName + "/pdb_config.json");
            if (configFile.exists && configFile.open("r")) {
                configFile.encoding = "UTF-8";
                var content = configFile.read();
                configFile.close();
                if (content && content.length > 0) {
                    var config = JSON.parse(content);
                    if (config && config.pickerUrl && typeof config.pickerUrl === "string") {
                        pickerUrl = config.pickerUrl;
                        if (pickerUrl.indexOf("/picker") === -1 && pickerUrl.charAt(pickerUrl.length - 1) !== "/") {
                            pickerUrl = pickerUrl + "/picker/";
                        } else if (pickerUrl.charAt(pickerUrl.length - 1) !== "/") {
                            pickerUrl = pickerUrl + "/";
                        }
                    }
                }
            }
        }
    } catch (e) {
        if (typeof prlbLogger !== "undefined") {
            prlbLogger.log("PICKER", "DEBUG", "Could not read pdb_config.json, using default URL: " + e.toString());
        }
    }

    function isLocalPickerUrl(url) {
        if (!url) return false;
        var lowered = String(url).toLowerCase();
        return (
            lowered.indexOf("127.0.0.1:4311") !== -1 ||
            lowered.indexOf("localhost:4311") !== -1
        );
    }

    function runShellCommand(command) {
        try {
            if (typeof app !== "undefined" && app && typeof app.system === "function") {
                app.system(command);
                return true;
            }
        } catch (e1) { }

        try {
            if (typeof system !== "undefined" && system && typeof system.callSystem === "function") {
                system.callSystem(command);
                return true;
            }
        } catch (e2) { }

        return false;
    }

    function ensureWindowsBridgeRunningIfLocal(url) {
        if (!isLocalPickerUrl(url)) {
            return;
        }
        try {
            var rootDir = scriptDir.parent;
            if (!rootDir || !rootDir.exists) {
                return;
            }

            var startScript = new File(rootDir.fsName + "/server-windows/start-pdb-bridge.cmd");
            if (!startScript.exists) {
                if (typeof prlbLogger !== "undefined") {
                    prlbLogger.log("PICKER", "WARN", "server-windows start script not found. Skipping auto-start.");
                }
                return;
            }

            var command = 'cmd.exe /c ""' + startScript.fsName + '" -EnsureRunning -WaitReady -Silent -NoPause"';
            runShellCommand(command);
        } catch (e) {
            if (typeof prlbLogger !== "undefined") {
                prlbLogger.log("PICKER", "WARN", "Auto-start bridge check failed: " + e.toString());
            }
        }
    }

    try {
        var osName = $.os ? String($.os).toLowerCase() : "";
        if (osName.indexOf("mac") !== -1) {
            var safeUrl = pickerUrl.replace(/"/g, "\\\"");
            var openedByShell = runShellCommand('open "' + safeUrl + '"');
            if (!openedByShell) {
                var macTempFolder = Folder.temp;
                if (!macTempFolder || !macTempFolder.exists) {
                    macTempFolder = new Folder(scriptDirPath + "/../temp");
                    if (!macTempFolder.exists) macTempFolder.create();
                }
                var htmlFile = new File(macTempFolder.fsName + "/ProofLab_Picker_" + (new Date().getTime()) + ".html");
                if (htmlFile.open("w")) {
                    htmlFile.write('<html><head><meta http-equiv="refresh" content="0;url=' + pickerUrl + '"></head><body>Opening picker...</body></html>');
                    htmlFile.close();
                    htmlFile.execute();
                } else {
                    throw new Error("Unable to open temporary browser launcher file");
                }
            }
        } else {
            ensureWindowsBridgeRunningIfLocal(pickerUrl);
            var tempFolder = Folder.temp;
            if (!tempFolder || !tempFolder.exists) {
                tempFolder = new Folder(scriptDirPath + "/../temp");
                if (!tempFolder.exists) tempFolder.create();
            }
            var urlFile = new File(tempFolder.fsName + "/ProofLab_Picker_" + (new Date().getTime()) + ".url");
            urlFile.open("w");
            urlFile.write("[InternetShortcut]\r\nURL=" + pickerUrl + "\r\n");
            urlFile.close();
            urlFile.execute();
            urlFile.remove();
        }
    } catch (e) {
        alert("Could not open PDB Picker in browser.\n\nURL: " + pickerUrl + "\n\nError: " + e.toString());
    }
})();
