"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveImageAnalysisRuntimeStatus = exports.hydrateImageAnalysisRuntimeStatus = void 0;
const auth_handler_1 = require("../../cliproxy/auth/auth-handler");
const remote_proxy_client_1 = require("../../cliproxy/services/remote-proxy-client");
const remote_auth_fetcher_1 = require("../../cliproxy/services/remote-auth-fetcher");
const proxy_target_resolver_1 = require("../../cliproxy/proxy/proxy-target-resolver");
const provider_capabilities_1 = require("../../cliproxy/provider-capabilities");
const stats_fetcher_1 = require("../../cliproxy/services/stats-fetcher");
const unified_config_types_1 = require("../../config/unified-config-types");
const image_analysis_backend_resolver_1 = require("./image-analysis-backend-resolver");
const defaultDeps = {
    checkRemoteProxy: (...args) => (0, remote_proxy_client_1.checkRemoteProxy)(...args),
    fetchRemoteAuthStatus: (...args) => (0, remote_auth_fetcher_1.fetchRemoteAuthStatus)(...args),
    getAuthStatus: (...args) => (0, auth_handler_1.getAuthStatus)(...args),
    getProxyTarget: () => (0, proxy_target_resolver_1.getProxyTarget)(),
    initializeAccounts: () => (0, auth_handler_1.initializeAccounts)(),
    isCliproxyRunning: () => (0, stats_fetcher_1.isCliproxyRunning)(),
};
function mergeDefinedDeps(defaults, overrides) {
    const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, value]) => value !== undefined));
    return { ...defaults, ...definedOverrides };
}
async function resolveAuthReadiness(status, deps) {
    if (!status.backendId || !status.model || !(0, provider_capabilities_1.isCLIProxyProvider)(status.backendId)) {
        return {
            authReadiness: 'not-needed',
            authProvider: null,
            authDisplayName: null,
            authReason: null,
        };
    }
    const authProvider = status.backendId;
    const authDisplayName = (0, provider_capabilities_1.getProviderDisplayName)(authProvider);
    try {
        let authenticated = false;
        const target = deps.getProxyTarget();
        if (target.isRemote) {
            const remoteStatuses = await deps.fetchRemoteAuthStatus(target);
            authenticated = remoteStatuses.some((entry) => entry.provider === authProvider && entry.authenticated);
        }
        else {
            deps.initializeAccounts();
            authenticated = deps.getAuthStatus(authProvider).authenticated;
        }
        return {
            authReadiness: authenticated ? 'ready' : 'missing',
            authProvider,
            authDisplayName,
            authReason: authenticated
                ? null
                : `${authDisplayName} auth is missing. Run "ccs ${authProvider} --auth" to enable image analysis.`,
        };
    }
    catch (error) {
        return {
            authReadiness: 'unknown',
            authProvider,
            authDisplayName,
            authReason: `CCS could not verify ${authDisplayName} auth readiness: ${error.message}`,
        };
    }
}
async function resolveProxyReadiness(status, deps) {
    if (!status.backendId || !status.model) {
        return {
            proxyReadiness: 'not-needed',
            proxyReason: null,
        };
    }
    const target = deps.getProxyTarget();
    if (target.isRemote) {
        const remoteStatus = await deps.checkRemoteProxy({
            host: target.host,
            port: target.port,
            protocol: target.protocol,
            authToken: target.authToken,
            allowSelfSigned: target.allowSelfSigned,
        });
        return {
            proxyReadiness: remoteStatus.reachable ? 'remote' : 'unavailable',
            proxyReason: remoteStatus.reachable
                ? `Remote CLIProxy target ${target.host}:${target.port} is reachable.`
                : remoteStatus.error ||
                    `Remote CLIProxy target ${target.host}:${target.port} is unreachable.`,
        };
    }
    const reachable = await deps.isCliproxyRunning();
    return {
        proxyReadiness: reachable ? 'ready' : 'stopped',
        proxyReason: reachable
            ? 'Local CLIProxy service is reachable.'
            : 'Local CLIProxy service is idle. CCS will start it automatically when image analysis is needed.',
    };
}
function resolveEffectiveRuntime(status) {
    if (!status.enabled || !status.backendId || !status.model) {
        return {
            effectiveRuntimeMode: 'native-read',
            effectiveRuntimeReason: status.reason,
        };
    }
    if (status.authReadiness === 'missing' || status.authReadiness === 'unknown') {
        return {
            effectiveRuntimeMode: 'native-read',
            effectiveRuntimeReason: status.authReason,
        };
    }
    if (status.proxyReadiness === 'unavailable' || status.proxyReadiness === 'unknown') {
        return {
            effectiveRuntimeMode: 'native-read',
            effectiveRuntimeReason: status.proxyReason,
        };
    }
    return {
        effectiveRuntimeMode: 'cliproxy-image-analysis',
        effectiveRuntimeReason: status.status === 'attention' || status.status === 'hook-missing' ? status.reason : null,
    };
}
async function hydrateImageAnalysisRuntimeStatus(baseStatus, deps = {}) {
    const resolvedDeps = mergeDefinedDeps(defaultDeps, deps);
    const authStatus = await resolveAuthReadiness(baseStatus, resolvedDeps);
    const proxyStatus = await resolveProxyReadiness(baseStatus, resolvedDeps);
    const mergedStatus = {
        ...baseStatus,
        ...authStatus,
        ...proxyStatus,
    };
    return {
        ...mergedStatus,
        ...resolveEffectiveRuntime(mergedStatus),
    };
}
exports.hydrateImageAnalysisRuntimeStatus = hydrateImageAnalysisRuntimeStatus;
async function resolveImageAnalysisRuntimeStatus(context, config = unified_config_types_1.DEFAULT_IMAGE_ANALYSIS_CONFIG, deps = {}) {
    const baseStatus = (0, image_analysis_backend_resolver_1.resolveImageAnalysisStatus)(context, config);
    return hydrateImageAnalysisRuntimeStatus(baseStatus, deps);
}
exports.resolveImageAnalysisRuntimeStatus = resolveImageAnalysisRuntimeStatus;
//# sourceMappingURL=image-analysis-runtime-status.js.map