"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.ArtifactType = void 0;
exports.emptyRegistry = emptyRegistry;
exports.getRegistryPath = getRegistryPath;
exports.readRegistry = readRegistry;
exports.writeRegistry = writeRegistry;
exports.buildEntryId = buildEntryId;
exports.recordInstallation = recordInstallation;
exports.pruneMissingArtifacts = pruneMissingArtifacts;
exports.getStaleInstallations = getStaleInstallations;
exports.readCliVersion = readCliVersion;
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const REGISTRY_PROJECT = 'mabl-cli';
const REGISTRY_FILE = 'agent-installations.json';
const REGISTRY_SCHEMA_VERSION = 1;
const MAX_PARENT_DIRS_TO_WALK = 10;
const CLI_PACKAGE_NAME_PREFIXES = [
    '@mablhq/mabl-cli',
    '@mablhq-internal/mabl-cli',
];
var ArtifactType;
(function (ArtifactType) {
    ArtifactType["McpEntry"] = "mcp-entry";
    ArtifactType["Skill"] = "skill";
    ArtifactType["Snippet"] = "snippet";
})(ArtifactType || (exports.ArtifactType = ArtifactType = {}));
function emptyRegistry() {
    return { version: REGISTRY_SCHEMA_VERSION, installations: [] };
}
function getRegistryPath() {
    return path.join(getConfigDir(), REGISTRY_FILE);
}
function readRegistry() {
    const filePath = getRegistryPath();
    if (!fs.existsSync(filePath)) {
        return emptyRegistry();
    }
    try {
        const raw = fs.readFileSync(filePath, 'utf8');
        if (raw.trim().length === 0) {
            return emptyRegistry();
        }
        const parsed = JSON.parse(raw);
        if (!parsed ||
            typeof parsed.version !== 'number' ||
            parsed.version > REGISTRY_SCHEMA_VERSION ||
            !Array.isArray(parsed.installations)) {
            return emptyRegistry();
        }
        return {
            version: REGISTRY_SCHEMA_VERSION,
            installations: parsed.installations.filter(isWellFormedEntry),
        };
    }
    catch {
        return emptyRegistry();
    }
}
function writeRegistry(registry) {
    const filePath = getRegistryPath();
    fs.mkdirSync(path.dirname(filePath), { recursive: true });
    const tempPath = `${filePath}.tmp-${process.pid}`;
    fs.writeFileSync(tempPath, JSON.stringify(registry, undefined, 2) + '\n', 'utf8');
    fs.renameSync(tempPath, filePath);
}
function buildEntryId(target, scope, projectPath) {
    if (projectPath) {
        return `${target}:${scope}:${projectPath}`;
    }
    return `${target}:${scope}`;
}
function recordInstallation(entry) {
    const registry = readRegistry();
    registry.installations = registry.installations.filter((existing) => existing.id !== entry.id);
    registry.installations.push(entry);
    writeRegistry(registry);
}
function pruneMissingArtifacts() {
    const registry = readRegistry();
    const pruned = [];
    const remaining = [];
    for (const entry of registry.installations) {
        if (isPrimaryArtifactMissing(entry)) {
            pruned.push(entry);
        }
        else {
            remaining.push(entry);
        }
    }
    if (pruned.length > 0) {
        registry.installations = remaining;
        writeRegistry(registry);
    }
    return { pruned, remaining };
}
function getStaleInstallations(entries, currentVersion) {
    return entries.filter((entry) => entry.cliVersion !== currentVersion);
}
function readCliVersion() {
    let dir = __dirname;
    for (let i = 0; i < MAX_PARENT_DIRS_TO_WALK; i++) {
        const candidate = path.join(dir, 'package.json');
        if (fs.existsSync(candidate)) {
            try {
                const pkg = JSON.parse(fs.readFileSync(candidate, 'utf8'));
                if (pkg.name && isCliPackageName(pkg.name) && pkg.version) {
                    return pkg.version;
                }
            }
            catch {
            }
        }
        const parent = path.dirname(dir);
        if (parent === dir) {
            break;
        }
        dir = parent;
    }
    return undefined;
}
function isCliPackageName(name) {
    return CLI_PACKAGE_NAME_PREFIXES.some((prefix) => name.startsWith(prefix));
}
function isPrimaryArtifactMissing(entry) {
    const skill = entry.artifacts.find((a) => a.type === ArtifactType.Skill);
    if (!skill) {
        return true;
    }
    return !fs.existsSync(skill.path);
}
function isWellFormedEntry(value) {
    if (!value || typeof value !== 'object') {
        return false;
    }
    const e = value;
    return (typeof e.id === 'string' &&
        typeof e.target === 'string' &&
        typeof e.scope === 'string' &&
        typeof e.cliVersion === 'string' &&
        typeof e.installedAt === 'string' &&
        Array.isArray(e.artifacts));
}
function getConfigDir() {
    const home = os.homedir();
    if (process.platform === 'darwin') {
        return path.join(home, 'Library', 'Preferences', REGISTRY_PROJECT);
    }
    if (process.platform === 'win32') {
        const appData = process.env.APPDATA ?? path.join(home, 'AppData', 'Roaming');
        return path.join(appData, REGISTRY_PROJECT, 'Config');
    }
    if (process.env.XDG_CONFIG_HOME &&
        path.isAbsolute(process.env.XDG_CONFIG_HOME)) {
        return path.join(process.env.XDG_CONFIG_HOME, REGISTRY_PROJECT);
    }
    return path.join(home, '.config', REGISTRY_PROJECT);
}
