"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.runSkillCommand = runSkillCommand;
const path = __importStar(require("path"));
const bootstrap_1 = require("../bootstrap");
const cliAnalyzeService_1 = require("../services/cliAnalyzeService");
const traceProcessorService_1 = require("../../services/traceProcessorService");
const skillExecutor_1 = require("../../services/skillEngine/skillExecutor");
const skillLoader_1 = require("../../services/skillEngine/skillLoader");
const stdio_1 = require("../io/stdio");
async function runSkillCommand(args) {
    const tracePath = path.resolve(args.trace);
    (0, bootstrap_1.bootstrap)({ envFile: args.envFile, sessionDir: args.sessionDir, requireLlm: false });
    const format = args.format ?? 'text';
    const service = new cliAnalyzeService_1.CliAnalyzeService();
    try {
        const params = parseParams(args.params);
        const { traceId, result } = await (0, stdio_1.withConsoleLogToStderr)(format !== 'text', async () => {
            await (0, skillLoader_1.ensureSkillRegistryInitialized)();
            const skill = skillLoader_1.skillRegistry.getSkill(args.skillId);
            if (!skill) {
                throw new Error(`unknown skill: ${args.skillId}`);
            }
            const loadedTraceId = await service.loadTrace(tracePath);
            const executor = (0, skillExecutor_1.createSkillExecutor)((0, traceProcessorService_1.getTraceProcessorService)(), undefined, (event) => {
                if (format === 'ndjson') {
                    process.stdout.write(`${JSON.stringify({ type: 'event', event })}\n`);
                }
            });
            executor.setFragmentRegistry(skillLoader_1.skillRegistry.getFragmentCache());
            executor.registerSkills(skillLoader_1.skillRegistry.getAllSkills());
            const skillResult = await executor.execute(args.skillId, loadedTraceId, params);
            return { traceId: loadedTraceId, result: skillResult };
        });
        writeSkillOutput(format, {
            tracePath,
            traceId,
            skillId: args.skillId,
            params,
            result,
        });
        return result.success === false ? 1 : 0;
    }
    catch (err) {
        writeError(format, err.message);
        return 1;
    }
    finally {
        await service.shutdown();
    }
}
function parseParams(raw) {
    if (!raw || !raw.trim())
        return {};
    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
        throw new Error('--params must be a JSON object');
    }
    return parsed;
}
function writeSkillOutput(format, payload) {
    const result = payload.result;
    const ok = result?.success !== false;
    if (format === 'json') {
        console.log(JSON.stringify({ ok, ...payload }, null, 2));
        return;
    }
    if (format === 'ndjson') {
        console.log(JSON.stringify({ type: 'complete', ok, ...payload }));
        return;
    }
    console.log(JSON.stringify(payload.result, null, 2));
}
function writeError(format, message) {
    if (format === 'json' || format === 'ndjson') {
        console.error(JSON.stringify({ ok: false, type: 'error', error: message }));
    }
    else {
        console.error(`Error: ${message}`);
    }
}
//# sourceMappingURL=skill.js.map