"use strict";
/**
 * WebSearch Hook Installer
 *
 * Manages installation and uninstallation of the legacy WebSearch hook runtime.
 *
 * @module utils/websearch/hook-installer
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uninstallWebSearchHook = exports.installWebSearchHook = exports.hasWebSearchHook = exports.removeMigrationMarker = exports.getMigrationMarkerPath = exports.getWebSearchHookConfig = exports.getHookPath = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ui_1 = require("../ui");
const config_manager_1 = require("../config-manager");
const hook_config_1 = require("./hook-config");
const config_loader_facade_1 = require("../../config/config-loader-facade");
// Re-export from hook-config for backward compatibility
var hook_config_2 = require("./hook-config");
Object.defineProperty(exports, "getHookPath", { enumerable: true, get: function () { return hook_config_2.getHookPath; } });
Object.defineProperty(exports, "getWebSearchHookConfig", { enumerable: true, get: function () { return hook_config_2.getWebSearchHookConfig; } });
// Hook file name
const WEBSEARCH_HOOK = 'websearch-transformer.cjs';
function hasMatchingHookContents(sourcePath, destinationPath) {
    if (!fs.existsSync(destinationPath)) {
        return false;
    }
    const source = fs.readFileSync(sourcePath);
    try {
        const destination = fs.readFileSync(destinationPath);
        return source.equals(destination);
    }
    catch (error) {
        if (process.env.CCS_DEBUG) {
            console.error((0, ui_1.warn)(`Existing WebSearch hook is unreadable; reinstalling: ${error.message}`));
        }
        return false;
    }
}
function getTempHookPath(hookPath) {
    const uniqueSuffix = `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
    return `${hookPath}.${uniqueSuffix}.tmp`;
}
function getMigrationMarkerPath() {
    return path.join((0, config_manager_1.getCcsDir)(), '.hook-migrated');
}
exports.getMigrationMarkerPath = getMigrationMarkerPath;
function removeMigrationMarker() {
    try {
        const markerPath = getMigrationMarkerPath();
        if (fs.existsSync(markerPath)) {
            fs.unlinkSync(markerPath);
        }
    }
    catch (error) {
        if (process.env.CCS_DEBUG) {
            console.error((0, ui_1.warn)(`removeMigrationMarker failed: ${error.message}`));
        }
    }
}
exports.removeMigrationMarker = removeMigrationMarker;
/**
 * Check if WebSearch hook is installed
 */
function hasWebSearchHook() {
    return fs.existsSync((0, hook_config_1.getHookPath)());
}
exports.hasWebSearchHook = hasWebSearchHook;
/**
 * Install WebSearch hook to ~/.ccs/hooks/
 *
 * This hook now serves as a compatibility fallback and a shared provider runtime
 * for the first-class CCS WebSearch MCP server.
 *
 * @returns true if hook installed successfully
 */
function installWebSearchHook() {
    try {
        const wsConfig = (0, config_loader_facade_1.getWebSearchConfig)();
        // Skip if disabled
        if (!wsConfig.enabled) {
            if (process.env.CCS_DEBUG) {
                console.error((0, ui_1.info)('WebSearch disabled - skipping hook install'));
            }
            return false;
        }
        // Ensure hooks directory exists
        const hooksDir = (0, config_manager_1.getCcsHooksDir)();
        if (!fs.existsSync(hooksDir)) {
            fs.mkdirSync(hooksDir, { recursive: true, mode: 0o700 });
        }
        const hookPath = (0, hook_config_1.getHookPath)();
        // Find the bundled hook script
        // In npm package: node_modules/ccs/lib/hooks/
        // In development: lib/hooks/
        const possiblePaths = [
            path.join(__dirname, '..', '..', '..', 'lib', 'hooks', WEBSEARCH_HOOK),
            path.join(__dirname, '..', '..', 'lib', 'hooks', WEBSEARCH_HOOK),
            path.join(__dirname, '..', 'lib', 'hooks', WEBSEARCH_HOOK),
        ];
        let sourcePath = null;
        for (const p of possiblePaths) {
            if (fs.existsSync(p)) {
                sourcePath = p;
                break;
            }
        }
        if (!sourcePath) {
            if (process.env.CCS_DEBUG) {
                console.error((0, ui_1.warn)(`WebSearch hook source not found: ${WEBSEARCH_HOOK}`));
            }
            return false;
        }
        // Avoid rewriting the shared hook binary when the bundled script is unchanged.
        if (hasMatchingHookContents(sourcePath, hookPath)) {
            return true;
        }
        // Copy hook to ~/.ccs/hooks/ via a unique temp path so concurrent installers
        // do not contend on the same file.
        const tempHookPath = getTempHookPath(hookPath);
        try {
            fs.copyFileSync(sourcePath, tempHookPath);
            fs.chmodSync(tempHookPath, 0o755);
            try {
                fs.renameSync(tempHookPath, hookPath);
            }
            catch (renameError) {
                const errorCode = renameError.code;
                if (errorCode !== 'EEXIST' && errorCode !== 'EPERM') {
                    throw renameError;
                }
                fs.copyFileSync(tempHookPath, hookPath);
                fs.chmodSync(hookPath, 0o755);
                fs.unlinkSync(tempHookPath);
            }
        }
        finally {
            if (fs.existsSync(tempHookPath)) {
                fs.unlinkSync(tempHookPath);
            }
        }
        if (process.env.CCS_DEBUG) {
            console.error((0, ui_1.info)(`Installed WebSearch hook: ${hookPath}`));
        }
        // Note: Hook registration is handled by ensureProfileHooks() in profile-hook-injector.ts
        // which writes to per-profile settings (~/.ccs/<profile>.settings.json)
        // Global settings (~/.claude/settings.json) are NOT modified here
        return true;
    }
    catch (error) {
        if (process.env.CCS_DEBUG) {
            console.error((0, ui_1.warn)(`Failed to install WebSearch hook: ${error.message}`));
        }
        return false;
    }
}
exports.installWebSearchHook = installWebSearchHook;
/**
 * Uninstall WebSearch hook from ~/.ccs/hooks/
 *
 * Note: Does NOT touch global ~/.claude/settings.json.
 * Profile-specific hooks are removed when ~/.ccs/ is deleted.
 *
 * @returns true if hook uninstalled successfully
 */
function uninstallWebSearchHook() {
    try {
        const hookPath = (0, hook_config_1.getHookPath)();
        if (fs.existsSync(hookPath)) {
            fs.unlinkSync(hookPath);
            if (process.env.CCS_DEBUG) {
                console.error((0, ui_1.info)(`Uninstalled WebSearch hook: ${hookPath}`));
            }
        }
        // Remove migration marker (so fresh install re-runs migration)
        removeMigrationMarker();
        // Note: Do NOT call removeHookConfig() - global settings should not be touched.
        // Per-profile hooks in ~/.ccs/*.settings.json are cleaned up when ~/.ccs/ is deleted.
        return true;
    }
    catch (error) {
        if (process.env.CCS_DEBUG) {
            console.error((0, ui_1.warn)(`Failed to uninstall WebSearch hook: ${error.message}`));
        }
        return false;
    }
}
exports.uninstallWebSearchHook = uninstallWebSearchHook;
//# sourceMappingURL=hook-installer.js.map