"use strict";
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2024-2026 Gracker (Chris)
// This file is part of SmartPerfetto. See LICENSE for details.
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.CodebaseRegistry = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const crypto_1 = require("crypto");
const CODEBASE_KINDS = ['app_source', 'aosp', 'kernel_source', 'oem_sdk'];
function consentHash(input) {
    return (0, crypto_1.createHash)('sha256')
        .update(JSON.stringify(input))
        .digest('hex')
        .slice(0, 16);
}
function toSummary(ref) {
    return {
        codebaseId: ref.codebaseId,
        kind: ref.kind,
        displayName: ref.displayName,
        ...(ref.commitHash ? { commitHash: ref.commitHash } : {}),
        ...(ref.vendor ? { vendor: ref.vendor } : {}),
        ...(ref.buildId ? { buildId: ref.buildId } : {}),
        indexGeneration: ref.indexGeneration,
        chunkCount: ref.chunkCount ?? 0,
        eligibleForSendToProvider: ref.consent.sendToProvider,
    };
}
class CodebaseRegistry {
    constructor(registryPath) {
        this.codebases = new Map();
        this.loaded = false;
        this.registryPath = registryPath;
    }
    load() {
        if (this.loaded)
            return;
        this.loaded = true;
        if (!fs.existsSync(this.registryPath))
            return;
        try {
            const parsed = JSON.parse(fs.readFileSync(this.registryPath, 'utf-8'));
            if (parsed.schemaVersion !== 1 || !Array.isArray(parsed.codebases))
                return;
            for (const ref of parsed.codebases) {
                this.codebases.set(ref.codebaseId, ref);
            }
        }
        catch {
            // Preserve corrupt registry for operator inspection.
        }
    }
    register(input) {
        this.load();
        if (!CODEBASE_KINDS.includes(input.kind)) {
            throw new Error(`Unsupported codebase kind: ${input.kind}`);
        }
        const rootRealpath = input.rootRealpath ?? fs.realpathSync(input.rootPath);
        const now = Date.now();
        const ref = {
            codebaseId: `cb_${(0, crypto_1.randomUUID)()}`,
            kind: input.kind,
            displayName: input.displayName,
            rootPath: input.rootPath,
            rootRealpath,
            ...(input.commitHash ? { commitHash: input.commitHash } : {}),
            ...(input.vendor ? { vendor: input.vendor } : {}),
            ...(input.buildId ? { buildId: input.buildId } : {}),
            ...(input.pathFilters ? { pathFilters: input.pathFilters } : {}),
            ...(input.excludeGlobs ? { excludeGlobs: input.excludeGlobs } : {}),
            ...(input.symbolMapPaths ? { symbolMapPaths: input.symbolMapPaths } : {}),
            ...(input.licenseTag ? { licenseTag: input.licenseTag } : {}),
            consent: {
                sendToProvider: input.sendToProvider ?? false,
                consentedAt: now,
                consentedBy: input.consentedBy ?? input.userId ?? 'local-user',
                consentHash: consentHash({
                    kind: input.kind,
                    rootRealpath,
                    commitHash: input.commitHash,
                    buildId: input.buildId,
                    vendor: input.vendor,
                }),
            },
            indexGeneration: 1,
            ...(input.tenantId ? { tenantId: input.tenantId } : {}),
            ...(input.workspaceId ? { workspaceId: input.workspaceId } : {}),
            ...(input.userId ? { userId: input.userId } : {}),
            createdAt: now,
            updatedAt: now,
        };
        this.codebases.set(ref.codebaseId, ref);
        this.persist();
        return ref;
    }
    get(codebaseId) {
        this.load();
        return this.codebases.get(codebaseId);
    }
    list() {
        this.load();
        return Array.from(this.codebases.values()).map(toSummary);
    }
    updateIngestStatus(codebaseId, patch) {
        this.load();
        const existing = this.codebases.get(codebaseId);
        if (!existing)
            return;
        this.codebases.set(codebaseId, {
            ...existing,
            ...patch,
            updatedAt: Date.now(),
        });
        this.persist();
    }
    persist() {
        const dir = path.dirname(this.registryPath);
        if (!fs.existsSync(dir))
            fs.mkdirSync(dir, { recursive: true });
        const tmp = `${this.registryPath}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;
        const envelope = {
            schemaVersion: 1,
            codebases: Array.from(this.codebases.values()),
        };
        fs.writeFileSync(tmp, JSON.stringify(envelope, null, 2), 'utf-8');
        fs.renameSync(tmp, this.registryPath);
    }
}
exports.CodebaseRegistry = CodebaseRegistry;
//# sourceMappingURL=codebaseRegistry.js.map