"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.runQueryCommand = runQueryCommand;
const path = __importStar(require("path"));
const bootstrap_1 = require("../bootstrap");
const cliAnalyzeService_1 = require("../services/cliAnalyzeService");
const traceProcessorService_1 = require("../../services/traceProcessorService");
const stdio_1 = require("../io/stdio");
async function runQueryCommand(args) {
    const tracePath = path.resolve(args.trace);
    (0, bootstrap_1.bootstrap)({ envFile: args.envFile, sessionDir: args.sessionDir, requireLlm: false });
    const service = new cliAnalyzeService_1.CliAnalyzeService();
    const format = args.format ?? 'text';
    try {
        const { traceId, result } = await (0, stdio_1.withConsoleLogToStderr)(format !== 'text', async () => {
            const loadedTraceId = await service.loadTrace(tracePath);
            const queryResult = await (0, traceProcessorService_1.getTraceProcessorService)().query(loadedTraceId, args.sql);
            return { traceId: loadedTraceId, result: queryResult };
        });
        writeQueryOutput(format, { tracePath, traceId, sql: args.sql, result });
        return result.error ? 1 : 0;
    }
    catch (err) {
        writeError(format, err.message);
        return 1;
    }
    finally {
        await service.shutdown();
    }
}
function writeQueryOutput(format, payload) {
    if (format === 'json') {
        console.log(JSON.stringify({ ok: !payload.result.error, ...payload }, null, 2));
        return;
    }
    if (format === 'ndjson') {
        console.log(JSON.stringify({
            type: 'metadata',
            tracePath: payload.tracePath,
            traceId: payload.traceId,
            sql: payload.sql,
            columns: payload.result.columns,
            durationMs: payload.result.durationMs,
        }));
        for (const row of payload.result.rows) {
            console.log(JSON.stringify({ type: 'row', row: rowToObject(payload.result.columns, row) }));
        }
        console.log(JSON.stringify({ type: 'complete', ok: !payload.result.error, rowCount: payload.result.rows.length }));
        return;
    }
    if (payload.result.error)
        console.error(`Error: ${payload.result.error}`);
    printTable(payload.result);
    console.log(`\n${payload.result.rows.length} row(s), ${payload.result.durationMs}ms`);
}
function writeError(format, message) {
    if (format === 'json' || format === 'ndjson') {
        console.error(JSON.stringify({ ok: false, type: 'error', error: message }));
    }
    else {
        console.error(`Error: ${message}`);
    }
}
function printTable(result) {
    if (result.columns.length === 0) {
        console.log('(no columns)');
        return;
    }
    const rows = result.rows.map((row) => row.map(formatCell));
    const widths = result.columns.map((col, i) => Math.min(80, Math.max(col.length, ...rows.map((row) => row[i]?.length ?? 0))));
    const pad = (value, width) => value.length > width ? `${value.slice(0, Math.max(0, width - 1))}…` : value.padEnd(width);
    console.log(result.columns.map((c, i) => pad(c, widths[i])).join('  '));
    console.log(widths.map((w) => '-'.repeat(w)).join('  '));
    for (const row of rows) {
        console.log(row.map((c, i) => pad(c, widths[i])).join('  '));
    }
}
function formatCell(value) {
    if (value === null || value === undefined)
        return '';
    if (typeof value === 'object')
        return JSON.stringify(value);
    return String(value);
}
function rowToObject(columns, row) {
    const obj = {};
    columns.forEach((col, index) => {
        obj[col] = row[index];
    });
    return obj;
}
//# sourceMappingURL=query.js.map