"use strict";
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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.BUILTIN_MODEL_CATALOG = exports.DEFAULT_MODEL_CATALOG_TTL_MS = void 0;
exports.validateModelCatalogManifest = validateModelCatalogManifest;
exports.getModelCatalog = getModelCatalog;
exports.getModelCatalogCacheStatus = getModelCatalogCacheStatus;
exports.readModelCatalogCache = readModelCatalogCache;
exports.writeModelCatalogCache = writeModelCatalogCache;
exports.listCatalogModels = listCatalogModels;
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
exports.DEFAULT_MODEL_CATALOG_TTL_MS = 24 * 60 * 60 * 1000;
exports.BUILTIN_MODEL_CATALOG = {
    version: 1,
    updatedAt: 'builtin',
    metadata: {
        recommendations: [
            { useCase: 'Best for coding', modelId: 'qwen2.5-coder:7b', reason: 'Best built-in local default for code edits; still validate with typecheck, tests, or smoke.' },
            { useCase: 'Best for research', modelId: 'llama3.1:8b', reason: 'General local reasoning default for summaries and workspace research.' },
            { useCase: 'Safe local fallback', modelId: 'llama3.1:8b', reason: 'Keeps prompts local when privacy matters more than raw capability.' },
            { useCase: 'Best for autonomy', modelId: 'strongest configured tool-capable model', reason: 'Use the strongest configured backend for long autonomous runs; keep validation and evidence review on.' },
            { useCase: 'Vision', modelId: 'llava:latest', reason: 'Use when image analysis is required and the model is pulled locally.' },
        ],
    },
    providers: {
        ollama: {
            metadata: { source: 'builtin' },
            models: [
                { id: 'qwen2.5-coder:7b', description: 'Balanced local coding default' },
                { id: 'llama3.1:8b', description: 'General local chat and reasoning model' },
                { id: 'llava:latest', description: 'Vision-capable local model for image analysis' },
            ],
        },
    },
};
function validateModelCatalogManifest(value) {
    if (!isRecord(value) || value.version !== 1 || typeof value.updatedAt !== 'string')
        return false;
    if (value.metadata !== undefined && !isRecord(value.metadata))
        return false;
    if (!isRecord(value.providers))
        return false;
    for (const [providerName, provider] of Object.entries(value.providers)) {
        if (!providerName.trim() || !isRecord(provider) || !Array.isArray(provider.models))
            return false;
        for (const model of provider.models) {
            if (!isRecord(model) || typeof model.id !== 'string' || !model.id.trim())
                return false;
            if (model.description !== undefined && typeof model.description !== 'string')
                return false;
            if (model.metadata !== undefined && !isRecord(model.metadata))
                return false;
        }
    }
    return true;
}
async function getModelCatalog(projectDir, options = {}) {
    const ttlMs = options.ttlMs ?? exports.DEFAULT_MODEL_CATALOG_TTL_MS;
    const now = options.now ?? new Date();
    const cache = await readModelCatalogCache(projectDir);
    const fresh = cache ? now.getTime() - Date.parse(cache.updatedAt) < ttlMs : false;
    if (cache && fresh && !options.forceRefresh)
        return cache;
    if (options.url && options.fetchJson) {
        try {
            const fetched = await options.fetchJson(options.url);
            if (validateModelCatalogManifest(fetched)) {
                const manifest = { ...fetched, updatedAt: fetched.updatedAt || now.toISOString() };
                await writeModelCatalogCache(projectDir, manifest);
                return manifest;
            }
        }
        catch {
            // Use stale cache or built-in fallback below.
        }
    }
    return cache ?? { ...exports.BUILTIN_MODEL_CATALOG, stale: true };
}
async function getModelCatalogCacheStatus(projectDir, now = new Date(), ttlMs = exports.DEFAULT_MODEL_CATALOG_TTL_MS) {
    const filePath = modelCatalogCachePath(projectDir);
    try {
        const stat = await fs.stat(filePath);
        const ageMs = now.getTime() - stat.mtimeMs;
        return { path: filePath, exists: true, fresh: ageMs < ttlMs, ageMs };
    }
    catch {
        return { path: filePath, exists: false, fresh: false, ageMs: Number.POSITIVE_INFINITY };
    }
}
async function readModelCatalogCache(projectDir) {
    try {
        const parsed = JSON.parse(await fs.readFile(modelCatalogCachePath(projectDir), 'utf-8'));
        return validateModelCatalogManifest(parsed) ? parsed : null;
    }
    catch {
        return null;
    }
}
async function writeModelCatalogCache(projectDir, manifest) {
    if (!validateModelCatalogManifest(manifest))
        throw new Error('Invalid model catalog manifest.');
    const filePath = modelCatalogCachePath(projectDir);
    await fs.mkdir(path.dirname(filePath), { recursive: true });
    const tmpPath = `${filePath}.tmp`;
    await fs.writeFile(tmpPath, JSON.stringify(manifest, null, 2), 'utf-8');
    await fs.rename(tmpPath, filePath);
}
function listCatalogModels(manifest, provider) {
    return manifest.providers[provider]?.models ?? [];
}
function modelCatalogCachePath(projectDir) {
    return path.join(projectDir, '.harness', 'cache', 'model-catalog.json');
}
function isRecord(value) {
    return typeof value === 'object' && value !== null && !Array.isArray(value);
}
//# sourceMappingURL=modelCatalog.js.map