"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.
Object.defineProperty(exports, "__esModule", { value: true });
const traceProcessorService_1 = require("../services/traceProcessorService");
const skillAnalysisAdapter_1 = require("../services/skillEngine/skillAnalysisAdapter");
const httpValue_1 = require("../utils/httpValue");
class SkillController {
    constructor() {
        this.adapter = null;
        /**
         * List all available skills
         * GET /api/skills
         */
        this.listSkills = async (req, res) => {
            try {
                const adapter = this.getAdapter();
                const skills = await adapter.listSkills();
                res.json({
                    skills,
                    count: skills.length,
                });
            }
            catch (error) {
                console.error('[SkillController] Error listing skills:', error);
                const errorResponse = {
                    error: 'Failed to list skills',
                    details: error instanceof Error ? error.message : 'Unknown error',
                };
                res.status(500).json(errorResponse);
            }
        };
        /**
         * Get skill details
         * GET /api/skills/:skillId
         */
        this.getSkillDetail = async (req, res) => {
            try {
                const skillId = (0, httpValue_1.toSingleString)(req.params.skillId);
                if (!skillId) {
                    return res.status(400).json({
                        error: 'Missing skill ID',
                        details: 'skillId is required',
                    });
                }
                const adapter = this.getAdapter();
                const skill = await adapter.getSkillDetail(skillId);
                if (!skill) {
                    return res.status(404).json({
                        error: 'Skill not found',
                        details: `No skill found with ID: ${skillId}`,
                    });
                }
                res.json({
                    id: skill.name,
                    name: skill.name,
                    version: skill.version,
                    type: skill.type,
                    meta: skill.meta,
                    triggers: skill.triggers,
                    prerequisites: skill.prerequisites,
                    steps: (skill.steps || []).map((s) => ({
                        id: s.id,
                        name: s.name,
                        type: s.type,
                        description: s.description,
                    })),
                    inputs: skill.inputs,
                    thresholds: skill.thresholds,
                    output: skill.output,
                });
            }
            catch (error) {
                console.error('[SkillController] Error getting skill detail:', error);
                const errorResponse = {
                    error: 'Failed to get skill detail',
                    details: error instanceof Error ? error.message : 'Unknown error',
                };
                res.status(500).json(errorResponse);
            }
        };
        /**
         * Execute a specific skill
         * POST /api/skills/execute/:skillId
         * Body: { traceId, packageName? }
         */
        this.executeSkill = async (req, res) => {
            try {
                const skillId = (0, httpValue_1.toSingleString)(req.params.skillId);
                const { traceId, packageName, params } = req.body;
                if (!skillId) {
                    return res.status(400).json({
                        error: 'Missing skill ID',
                        details: 'skillId is required in URL params',
                    });
                }
                if (!traceId) {
                    return res.status(400).json({
                        error: 'Missing trace ID',
                        details: 'traceId is required in request body',
                    });
                }
                const adapter = this.getAdapter();
                const request = {
                    traceId,
                    skillId,
                    packageName: typeof packageName === 'string' ? packageName : undefined,
                    params, // Pass custom skill parameters
                };
                const result = await adapter.analyze(request);
                res.json(result);
            }
            catch (error) {
                console.error('[SkillController] Error executing skill:', error);
                const errorResponse = {
                    error: 'Failed to execute skill',
                    details: error instanceof Error ? error.message : 'Unknown error',
                };
                res.status(500).json(errorResponse);
            }
        };
        /**
         * Analyze a trace with automatic skill detection
         * POST /api/skills/analyze
         * Body: { traceId, question, packageName? }
         */
        this.analyzeTrace = async (req, res) => {
            try {
                const { traceId, question, packageName, skillId } = req.body;
                if (!traceId) {
                    return res.status(400).json({
                        error: 'Missing trace ID',
                        details: 'traceId is required',
                    });
                }
                if (!question && !skillId) {
                    return res.status(400).json({
                        error: 'Missing question or skillId',
                        details: 'Either question or skillId is required',
                    });
                }
                const adapter = this.getAdapter();
                const request = {
                    traceId,
                    skillId,
                    question,
                    packageName,
                };
                const result = await adapter.analyze(request);
                res.json(result);
            }
            catch (error) {
                console.error('[SkillController] Error analyzing trace:', error);
                const errorResponse = {
                    error: 'Failed to analyze trace',
                    details: error instanceof Error ? error.message : 'Unknown error',
                };
                res.status(500).json(errorResponse);
            }
        };
        /**
         * Detect intent from a question
         * POST /api/skills/detect-intent
         * Body: { question }
         */
        this.detectIntent = async (req, res) => {
            try {
                const { question } = req.body;
                if (!question) {
                    return res.status(400).json({
                        error: 'Missing question',
                        details: 'question is required',
                    });
                }
                const adapter = this.getAdapter();
                await adapter.ensureInitialized();
                const skillId = adapter.detectIntent(question);
                if (!skillId) {
                    return res.json({
                        matched: false,
                        skillId: null,
                        message: 'No matching skill found for the given question',
                    });
                }
                const skill = await adapter.getSkillDetail(skillId);
                res.json({
                    matched: true,
                    skillId,
                    skillName: skill?.meta.display_name || skillId,
                    skillDescription: skill?.meta.description,
                });
            }
            catch (error) {
                console.error('[SkillController] Error detecting intent:', error);
                const errorResponse = {
                    error: 'Failed to detect intent',
                    details: error instanceof Error ? error.message : 'Unknown error',
                };
                res.status(500).json(errorResponse);
            }
        };
        /**
         * Detect vendor from trace
         * POST /api/skills/detect-vendor
         * Body: { traceId }
         */
        this.detectVendor = async (req, res) => {
            try {
                const { traceId } = req.body;
                if (!traceId) {
                    return res.status(400).json({
                        error: 'Missing trace ID',
                        details: 'traceId is required',
                    });
                }
                const adapter = this.getAdapter();
                const vendorResult = await adapter.detectVendor(traceId);
                res.json({
                    vendor: vendorResult.vendor,
                    confidence: vendorResult.confidence,
                });
            }
            catch (error) {
                console.error('[SkillController] Error detecting vendor:', error);
                const errorResponse = {
                    error: 'Failed to detect vendor',
                    details: error instanceof Error ? error.message : 'Unknown error',
                };
                res.status(500).json(errorResponse);
            }
        };
    }
    /**
     * Get or create the adapter instance
     */
    getAdapter() {
        if (!this.adapter) {
            const traceProcessor = (0, traceProcessorService_1.getTraceProcessorService)();
            this.adapter = (0, skillAnalysisAdapter_1.createSkillAnalysisAdapter)(traceProcessor);
        }
        return this.adapter;
    }
}
exports.default = SkillController;
//# sourceMappingURL=skillController.js.map