"use strict";
/**
 * Image Analysis Config Check
 *
 * Validates image_analysis configuration in config.yaml.
 * Checks: enabled status, provider_models, timeout, CLIProxy availability.
 */
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.fixImageAnalysisConfig = exports.runImageAnalysisCheck = void 0;
const unified_config_types_1 = require("../../config/unified-config-types");
const image_analysis_1 = require("../../utils/image-analysis");
const ui_1 = require("../../utils/ui");
const stats_fetcher_1 = require("../../cliproxy/services/stats-fetcher");
const config_generator_1 = require("../../cliproxy/config/config-generator");
const image_analyzer_hook_installer_1 = require("../../utils/hooks/image-analyzer-hook-installer");
const config_loader_facade_1 = require("../../config/config-loader-facade");
/**
 * Run image analysis configuration check
 */
async function runImageAnalysisCheck(results) {
    const config = (0, config_loader_facade_1.getImageAnalysisConfig)();
    // Check 1: Feature status
    if (!config.enabled) {
        results.details['Image Analysis'] = {
            status: 'OK',
            info: 'Disabled (using native Read)',
        };
        console.log(`  ${(0, ui_1.dim)('Status:')} Disabled`);
        console.log(`  ${(0, ui_1.dim)('Tip:')} Enable with: ccs config image-analysis --enable`);
        return;
    }
    // Feature is enabled - run validation checks
    console.log(`  ${(0, ui_1.ok)('Status:')} Enabled`);
    // Check 2: Provider models configured
    const providers = Object.keys(config.provider_models);
    if (providers.length === 0) {
        results.details['Image Analysis'] = {
            status: 'ERROR',
            info: 'No providers configured',
        };
        results.errors.push({
            name: 'Image Analysis',
            message: 'No provider models configured for image analysis',
            fix: 'ccs config image-analysis --set-model agy gemini-3-1-flash-preview',
        });
        console.log(`  ${(0, ui_1.warn)('Providers:')} None configured`);
        return;
    }
    console.log(`  ${(0, ui_1.ok)('Providers:')} ${providers.join(', ')}`);
    // Check 3: Timeout validation
    if (config.timeout < 10 || config.timeout > 600) {
        results.details['Image Analysis'] = {
            status: 'ERROR',
            info: `Invalid timeout: ${config.timeout}s`,
        };
        results.errors.push({
            name: 'Image Analysis',
            message: `Timeout ${config.timeout}s out of range (10-600)`,
            fix: 'ccs config image-analysis --timeout 60',
        });
        console.log(`  ${(0, ui_1.warn)('Timeout:')} ${config.timeout}s (invalid, must be 10-600)`);
        return;
    }
    console.log(`  ${(0, ui_1.ok)('Timeout:')} ${config.timeout}s`);
    const staleHookCount = (0, image_analysis_1.countManagedImageAnalysisHookFiles)();
    if (staleHookCount > 0) {
        results.warnings.push({
            name: 'Image Analysis',
            message: `${staleHookCount} stale CCS-managed image hook setting file(s) were detected`,
            fix: 'Run: ccs doctor --fix',
        });
        console.log(`  ${(0, ui_1.warn)('Hooks:')} ${staleHookCount} stale setting file(s) can be repaired`);
    }
    // Check 4: CLIProxy availability (only if enabled)
    const cliproxyAvailable = await (0, stats_fetcher_1.isCliproxyRunning)(config_generator_1.CLIPROXY_DEFAULT_PORT);
    if (!cliproxyAvailable) {
        results.details['Image Analysis'] = {
            status: 'WARN',
            info: 'Enabled; local CLIProxy will start on launch if needed',
        };
        results.warnings.push({
            name: 'Image Analysis',
            message: 'CLIProxy not running yet - CCS will start it automatically when ImageAnalysis is used',
            fix: 'Optional warm-up: ccs config',
        });
        console.log(`  ${(0, ui_1.warn)('CLIProxy:')} Idle at http://127.0.0.1:${config_generator_1.CLIPROXY_DEFAULT_PORT} (auto-start on launch)`);
        return;
    }
    console.log(`  ${(0, ui_1.ok)('CLIProxy:')} Available at http://127.0.0.1:${config_generator_1.CLIPROXY_DEFAULT_PORT}`);
    // All checks passed
    results.details['Image Analysis'] = {
        status: 'OK',
        info: `Enabled (${providers.length} providers)`,
    };
}
exports.runImageAnalysisCheck = runImageAnalysisCheck;
/**
 * Fix image analysis configuration issues
 */
async function fixImageAnalysisConfig() {
    const { updateConfig, loadOrCreateUnifiedConfig } = await Promise.resolve().then(() => __importStar(require('../../config/config-loader-facade')));
    const config = loadOrCreateUnifiedConfig();
    let fixed = false;
    const hadManagedToolReady = (0, image_analysis_1.hasImageAnalysisMcpReady)();
    const hadSharedHookReady = (0, image_analyzer_hook_installer_1.hasImageAnalyzerHook)();
    // Fix missing provider_models
    if (!config.image_analysis?.provider_models ||
        Object.keys(config.image_analysis.provider_models).length === 0) {
        config.image_analysis = {
            ...config.image_analysis,
            enabled: config.image_analysis?.enabled ?? true,
            timeout: config.image_analysis?.timeout ?? 60,
            provider_models: { ...unified_config_types_1.DEFAULT_IMAGE_ANALYSIS_CONFIG.provider_models },
        };
        fixed = true;
    }
    // Fix invalid timeout
    if (config.image_analysis &&
        (config.image_analysis.timeout < 10 || config.image_analysis.timeout > 600)) {
        config.image_analysis.timeout = 60;
        fixed = true;
    }
    if (fixed) {
        updateConfig({ image_analysis: config.image_analysis });
    }
    const repairStats = (0, image_analysis_1.repairImageAnalysisRuntimeState)();
    return (fixed ||
        repairStats.cleanedSettingsFiles > 0 ||
        repairStats.syncedInstances > 0 ||
        (!hadManagedToolReady && repairStats.managedToolReady) ||
        (!hadSharedHookReady && repairStats.sharedHookReady));
}
exports.fixImageAnalysisConfig = fixImageAnalysisConfig;
//# sourceMappingURL=image-analysis-check.js.map