"use strict";
/**
 * Image Analyzer Hook Installer
 *
 * Manages installation and uninstallation of the image analyzer hook.
 * This hook intercepts Read tool calls and analyzes image files via CLIProxy.
 *
 * @module utils/hooks/image-analyzer-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.uninstallImageAnalyzerHook = exports.installImageAnalyzerHook = exports.hasImageAnalyzerHook = exports.getImageAnalyzerHookConfig = exports.getImageAnalyzerHookPath = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ui_1 = require("../ui");
const image_analyzer_hook_configuration_1 = require("./image-analyzer-hook-configuration");
const config_manager_1 = require("../config-manager");
const image_analyzer_profile_hook_injector_1 = require("./image-analyzer-profile-hook-injector");
const hook_installer_1 = require("../image-analysis/hook-installer");
const config_loader_facade_1 = require("../../config/config-loader-facade");
// Re-export from hook-configuration for backward compatibility
var image_analyzer_hook_configuration_2 = require("./image-analyzer-hook-configuration");
Object.defineProperty(exports, "getImageAnalyzerHookPath", { enumerable: true, get: function () { return image_analyzer_hook_configuration_2.getImageAnalyzerHookPath; } });
Object.defineProperty(exports, "getImageAnalyzerHookConfig", { enumerable: true, get: function () { return image_analyzer_hook_configuration_2.getImageAnalyzerHookConfig; } });
// Hook file name
const IMAGE_ANALYZER_HOOK = 'image-analyzer-transformer.cjs';
const IMAGE_ANALYSIS_RUNTIME = 'image-analysis-runtime.cjs';
function getImageAnalysisRuntimeHookPath() {
    return path.join((0, config_manager_1.getCcsHooksDir)(), IMAGE_ANALYSIS_RUNTIME);
}
function getHookArtifacts() {
    return [
        { fileName: IMAGE_ANALYZER_HOOK, destinationPath: (0, image_analyzer_hook_configuration_1.getImageAnalyzerHookPath)() },
        {
            fileName: IMAGE_ANALYSIS_RUNTIME,
            destinationPath: getImageAnalysisRuntimeHookPath(),
        },
    ];
}
function resolveHookSourceBasePath(artifacts) {
    const possibleBasePaths = [
        path.join(__dirname, '..', '..', '..', 'lib', 'hooks'),
        path.join(__dirname, '..', '..', 'lib', 'hooks'),
        path.join(__dirname, '..', 'lib', 'hooks'),
    ];
    for (const basePath of possibleBasePaths) {
        if (artifacts.every(({ fileName }) => fs.existsSync(path.join(basePath, fileName)))) {
            return basePath;
        }
    }
    return null;
}
function artifactsMatch(sourcePath, destinationPath) {
    try {
        return fs.readFileSync(sourcePath).equals(fs.readFileSync(destinationPath));
    }
    catch {
        return false;
    }
}
/**
 * Check if image analyzer hook is installed
 */
function hasImageAnalyzerHook() {
    const artifacts = getHookArtifacts();
    if (!artifacts.every(({ destinationPath }) => fs.existsSync(destinationPath))) {
        return false;
    }
    const sourceBasePath = resolveHookSourceBasePath(artifacts);
    if (!sourceBasePath) {
        return true;
    }
    return artifacts.every(({ fileName, destinationPath }) => artifactsMatch(path.join(sourceBasePath, fileName), destinationPath));
}
exports.hasImageAnalyzerHook = hasImageAnalyzerHook;
/**
 * Install image analyzer hook to ~/.ccs/hooks/
 *
 * This hook intercepts Read calls and analyzes images via CLIProxy.
 *
 * @returns true if hook installed successfully
 */
function installImageAnalyzerHook() {
    try {
        const imageConfig = (0, config_loader_facade_1.getImageAnalysisConfig)();
        // Skip if disabled
        if (!imageConfig.enabled) {
            if (process.env.CCS_DEBUG) {
                console.error((0, ui_1.info)('Image analysis 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 artifacts = getHookArtifacts();
        const sourceBasePath = resolveHookSourceBasePath(artifacts);
        if (!sourceBasePath) {
            if (process.env.CCS_DEBUG) {
                console.error((0, ui_1.warn)(`Image analyzer hook source not found: ${IMAGE_ANALYZER_HOOK}`));
            }
            return false;
        }
        for (const { fileName, destinationPath } of artifacts) {
            fs.copyFileSync(path.join(sourceBasePath, fileName), destinationPath);
            fs.chmodSync(destinationPath, 0o755);
        }
        (0, hook_installer_1.installImageAnalysisPrompts)();
        if (process.env.CCS_DEBUG) {
            console.error((0, ui_1.info)(`Installed image analyzer hook runtime: ${hooksDir}`));
        }
        // Note: Hook registration is handled by ensureProfileHooks() in image-analyzer-profile-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 image analyzer hook: ${error.message}`));
        }
        return false;
    }
}
exports.installImageAnalyzerHook = installImageAnalyzerHook;
/**
 * Uninstall image analyzer 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 uninstallImageAnalyzerHook() {
    try {
        const artifactPaths = [(0, image_analyzer_hook_configuration_1.getImageAnalyzerHookPath)(), getImageAnalysisRuntimeHookPath()];
        for (const artifactPath of artifactPaths) {
            if (fs.existsSync(artifactPath)) {
                fs.unlinkSync(artifactPath);
                if (process.env.CCS_DEBUG) {
                    console.error((0, ui_1.info)(`Uninstalled image analyzer artifact: ${artifactPath}`));
                }
            }
        }
        // Remove migration marker (so fresh install re-runs migration)
        (0, image_analyzer_profile_hook_injector_1.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 image analyzer hook: ${error.message}`));
        }
        return false;
    }
}
exports.uninstallImageAnalyzerHook = uninstallImageAnalyzerHook;
//# sourceMappingURL=image-analyzer-hook-installer.js.map