"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.getDefaultSmartPerfettoSqlPackageDir = getDefaultSmartPerfettoSqlPackageDir;
exports.loadSmartPerfettoSqlPackage = loadSmartPerfettoSqlPackage;
exports.readSmartPerfettoSqlSymbol = readSmartPerfettoSqlSymbol;
/**
 * SmartPerfetto PerfettoSQL Package Loader (Spark Plan 03)
 *
 * Reads `backend/sql/smartperfetto/PACKAGE.json` plus the per-module
 * `.sql` files and returns a `SmartPerfettoSqlPackageContract` that the
 * runtime (workingTraceProcessor / claudeMcpServer) can boot via
 * `INCLUDE PERFETTO MODULE smartperfetto.*` once trace_processor_shell
 * supports add-sql-package on the http path.
 *
 * Until the boot path lands, callers can still issue the SQL directly via
 * existing `execute_sql` for parity, and the contract gives docs / agent
 * prompts a single source of truth for the canonical symbol names.
 */
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const sparkContracts_1 = require("../types/sparkContracts");
/**
 * Derive the actual SQL identifier from the dotted docs path. Perfetto
 * SQL identifiers cannot contain dots, so we mirror the stdlib convention
 * of underscore-separated names. Manifest entries can override via the
 * explicit `sqlName` field.
 */
function deriveSqlName(name) {
    return name.replace(/\./g, '_');
}
/** Default location for the SmartPerfetto SQL package directory. */
function getDefaultSmartPerfettoSqlPackageDir() {
    return path.resolve(__dirname, '../../sql/smartperfetto');
}
/** Read PACKAGE.json + verify all referenced .sql files exist. */
function loadSmartPerfettoSqlPackage(packageDir = getDefaultSmartPerfettoSqlPackageDir()) {
    const manifestPath = path.join(packageDir, 'PACKAGE.json');
    if (!fs.existsSync(manifestPath)) {
        return {
            ...(0, sparkContracts_1.makeSparkProvenance)({
                source: 'smartperfetto-sql-package',
                unsupportedReason: `PACKAGE.json not found at ${manifestPath}`,
            }),
            packageVersion: '0.0.0',
            symbols: [],
            coverage: [
                { sparkId: 3, planId: '03', status: 'unsupported' },
                { sparkId: 36, planId: '03', status: 'unsupported' },
            ],
        };
    }
    let manifest;
    try {
        manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
    }
    catch (err) {
        return {
            ...(0, sparkContracts_1.makeSparkProvenance)({
                source: 'smartperfetto-sql-package',
                unsupportedReason: `Failed to parse PACKAGE.json: ${err?.message ?? String(err)}`,
            }),
            packageVersion: '0.0.0',
            symbols: [],
            coverage: [{ sparkId: 3, planId: '03', status: 'unsupported' }],
        };
    }
    const symbols = [];
    const removed = [];
    for (const declared of manifest.symbols ?? []) {
        const sqlName = declared.sqlName ?? deriveSqlName(declared.name);
        const sqlPath = path.join(packageDir, declared.module);
        if (!fs.existsSync(sqlPath)) {
            removed.push({
                name: declared.name,
                sqlName,
                kind: declared.kind,
                module: declared.module,
                summary: declared.summary,
                signature: declared.signature,
                dependencies: declared.dependencies,
                stability: 'deprecated',
            });
            continue;
        }
        symbols.push({
            name: declared.name,
            sqlName,
            kind: declared.kind,
            module: declared.module,
            summary: declared.summary,
            signature: declared.signature,
            dependencies: declared.dependencies,
            stability: declared.stability ?? 'experimental',
        });
    }
    return {
        ...(0, sparkContracts_1.makeSparkProvenance)({ source: 'smartperfetto-sql-package' }),
        packageVersion: manifest.packageVersion,
        symbols,
        ...(removed.length > 0 ? { removed } : {}),
        bootSnippet: 'INCLUDE PERFETTO MODULE smartperfetto.*; -- pending trace_processor add-sql-package support',
        coverage: [
            {
                sparkId: 3,
                planId: '03',
                status: 'implemented',
                note: `${symbols.length} SmartPerfetto SQL symbols available.`,
            },
            {
                sparkId: 36,
                planId: '03',
                status: 'implemented',
                note: 'Boot snippet recorded; runtime activation lands once trace_processor_shell exposes add-sql-package over httpd.',
            },
        ],
    };
}
/** Return the raw SQL source for a registered symbol, or null. */
function readSmartPerfettoSqlSymbol(symbolName, packageDir = getDefaultSmartPerfettoSqlPackageDir()) {
    const contract = loadSmartPerfettoSqlPackage(packageDir);
    const symbol = contract.symbols.find(s => s.name === symbolName);
    if (!symbol)
        return null;
    const filePath = path.join(packageDir, symbol.module);
    if (!fs.existsSync(filePath))
        return null;
    return {
        module: symbol.module,
        sql: fs.readFileSync(filePath, 'utf-8'),
    };
}
//# sourceMappingURL=smartperfettoSqlPackage.js.map