"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.runCodebaseListCommand = runCodebaseListCommand;
exports.runCodebasePreviewCommand = runCodebasePreviewCommand;
exports.runCodebaseRegisterCommand = runCodebaseRegisterCommand;
exports.runCodebaseReindexCommand = runCodebaseReindexCommand;
exports.runCodebaseSymbolsCommand = runCodebaseSymbolsCommand;
const path = __importStar(require("path"));
const bootstrap_1 = require("../bootstrap");
const runtimePaths_1 = require("../../runtimePaths");
const ragStore_1 = require("../../services/ragStore");
const codebaseRegistry_1 = require("../../services/codebase/codebaseRegistry");
const pathSecurityGate_1 = require("../../services/codebase/pathSecurityGate");
const appSourceIngester_1 = require("../../services/rag/appSourceIngester");
const aospSourceIngester_1 = require("../../services/rag/aospSourceIngester");
const kernelSourceIngester_1 = require("../../services/rag/kernelSourceIngester");
const symbolResolver_1 = require("../../services/symbol/symbolResolver");
const registryPath = () => (0, runtimePaths_1.backendLogPath)('codebase_registry.json');
const ragStorePath = () => (0, runtimePaths_1.backendLogPath)('rag_store.json');
async function runCodebaseListCommand(args) {
    (0, bootstrap_1.bootstrap)({ envFile: args.envFile, sessionDir: args.sessionDir });
    const registry = new codebaseRegistry_1.CodebaseRegistry(registryPath());
    const codebases = registry.list();
    if (codebases.length === 0) {
        console.log('(no codebases registered)');
        return 0;
    }
    for (const ref of codebases) {
        console.log(`${ref.codebaseId}\t${ref.kind}\t${ref.displayName}\tchunks=${ref.chunkCount}\tprovider=${ref.eligibleForSendToProvider ? 'yes' : 'no'}`);
    }
    return 0;
}
async function runCodebasePreviewCommand(args) {
    const rootPath = path.resolve(args.rootPath);
    (0, bootstrap_1.bootstrap)({ envFile: args.envFile, sessionDir: args.sessionDir });
    const gate = new pathSecurityGate_1.PathSecurityGate({ allowlistRoots: [rootPath] });
    const preview = await gate.preview(rootPath);
    console.log(JSON.stringify({
        blocked: preview.blocked,
        blockedReason: preview.blockedReason,
        acceptedFileCount: preview.acceptedFiles.length,
        skippedFileCount: preview.skippedFiles.length,
        acceptedFiles: preview.acceptedFiles.slice(0, 50),
    }, null, 2));
    return preview.blocked ? 1 : 0;
}
async function runCodebaseRegisterCommand(args) {
    const rootPath = path.resolve(args.rootPath);
    (0, bootstrap_1.bootstrap)({ envFile: args.envFile, sessionDir: args.sessionDir });
    const gate = new pathSecurityGate_1.PathSecurityGate({ allowlistRoots: [rootPath] });
    const preview = await gate.preview(rootPath);
    if (preview.blocked) {
        console.error(`blocked: ${preview.blockedReason ?? 'path security gate rejected root'}`);
        return 1;
    }
    if (args.dryRun) {
        console.log(JSON.stringify({
            kind: args.kind ?? 'app_source',
            displayName: args.name ?? path.basename(rootPath),
            rootPath,
            acceptedFileCount: preview.acceptedFiles.length,
            skippedFileCount: preview.skippedFiles.length,
        }, null, 2));
        return 0;
    }
    const registry = new codebaseRegistry_1.CodebaseRegistry(registryPath());
    const ref = registry.register({
        kind: args.kind ?? 'app_source',
        displayName: args.name ?? path.basename(rootPath),
        rootPath,
        rootRealpath: preview.rootRealpath,
        sendToProvider: Boolean(args.sendToProvider),
        pathFilters: args.pathFilters,
        ...(args.vendor ? { vendor: args.vendor } : {}),
        ...(args.buildId ? { buildId: args.buildId } : {}),
        ...(args.commitHash ? { commitHash: args.commitHash } : {}),
        ...(args.licenseTag ? { licenseTag: args.licenseTag } : {}),
    });
    console.log(`${ref.codebaseId}\t${ref.displayName}`);
    return 0;
}
async function runCodebaseReindexCommand(args) {
    (0, bootstrap_1.bootstrap)({ envFile: args.envFile, sessionDir: args.sessionDir });
    const registry = new codebaseRegistry_1.CodebaseRegistry(registryPath());
    const ref = registry.get(args.codebaseId);
    if (!ref) {
        console.error(`Codebase not found: ${args.codebaseId}`);
        return 1;
    }
    const store = new ragStore_1.RagStore(ragStorePath());
    const gate = new pathSecurityGate_1.PathSecurityGate({ allowlistRoots: [ref.rootRealpath] });
    const result = await (ref.kind === 'kernel_source'
        ? new kernelSourceIngester_1.KernelSourceIngester(store, registry, gate).ingest(args.codebaseId)
        : ref.kind === 'aosp'
            ? new aospSourceIngester_1.AospSourceIngester(store, registry, gate).ingest(args.codebaseId)
            : new appSourceIngester_1.AppSourceIngester(store, registry, gate).ingest(args.codebaseId));
    console.log(JSON.stringify(result, null, 2));
    return result.errors.length > 0 ? 1 : 0;
}
async function runCodebaseSymbolsCommand(args) {
    (0, bootstrap_1.bootstrap)({ envFile: args.envFile, sessionDir: args.sessionDir });
    const registry = new codebaseRegistry_1.CodebaseRegistry(registryPath());
    const ref = args.codebaseId ? registry.get(args.codebaseId) : undefined;
    const resolver = new symbolResolver_1.SymbolResolver(new ragStore_1.RagStore(ragStorePath()));
    const result = ref?.kind === 'kernel_source'
        ? resolver.resolveKernel({ symbol: args.symbol, codebaseId: args.codebaseId, vendor: ref.vendor })
        : ref?.kind === 'aosp'
            ? resolver.resolveNative({ symbol: args.symbol, codebaseId: args.codebaseId })
            : resolver.resolveApp({
                symbol: args.symbol,
                codebaseId: args.codebaseId,
            });
    console.log(JSON.stringify(result, null, 2));
    return result.success ? 0 : 1;
}
//# sourceMappingURL=codebase.js.map