"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 });
exports.PromptTemplateService = void 0;
/**
 * Prompt Template Service
 *
 * Centralized management of AI prompt templates for trace analysis.
 * Provides unified interface for retrieving and formatting prompts.
 */
const prompts_1 = require("../config/prompts");
// ============================================================================
// Service
// ============================================================================
/**
 * Singleton service for managing prompt templates
 */
class PromptTemplateService {
    constructor() {
        this.templates = new Map();
        this.initializeDefaultTemplates();
    }
    /**
     * Get singleton instance
     */
    static getInstance() {
        if (!PromptTemplateService.instance) {
            PromptTemplateService.instance = new PromptTemplateService();
        }
        return PromptTemplateService.instance;
    }
    /**
     * Initialize default prompt templates
     */
    initializeDefaultTemplates() {
        // SQL Generation Template (using centralized prompts)
        this.addTemplate({
            name: 'sql-generation',
            system: `You are a Perfetto SQL expert. Generate accurate SQL queries to analyze trace data.

IMPORTANT RULES:
1. ONLY use tables listed in the schema below
2. All timestamps are in NANOSECONDS - convert to ms with /1e6 or seconds with /1e9
3. Use proper JOIN conditions with foreign keys (track_id, utid, upid)
4. Use thread_track for thread tracks, not track directly

${prompts_1.PROMPTS.SQL_GENERATION.withSchema}

{schema}

Example queries:
{examples}

Respond with ONLY one SQL query wrapped in \`\`\`sql ... \`\`\` code blocks. Do not include any explanation or additional text.`,
            user: '{question}',
            temperature: 0.3,
        });
        // SQL Fix Template (using centralized prompts)
        this.addTemplate({
            name: 'sql-fix',
            system: `You are a Perfetto SQL expert. Your task is to fix SQL queries that failed to execute.

[SQL EXECUTION ERROR]

${prompts_1.PROMPTS.ERROR_FIX.syntax}

Please FIX the SQL query and try again. Common issues:
- Wrong column names (check schema)
- Wrong table names (check schema)
- Syntax errors
- Type mismatches

Generate ONE corrected SQL query wrapped in \`\`\`sql ... \`\`\` code blocks. Do not include any explanation or additional text.`,
            user: '',
            temperature: 0.2,
        });
        // SQL Adjust Template (using centralized prompts)
        this.addTemplate({
            name: 'sql-adjust',
            system: `You are a Perfetto SQL expert. Your task is to adjust SQL queries that returned no results.

[QUERY RESULT - 0 ROWS]

${prompts_1.PROMPTS.ERROR_FIX.noResults}

This means:
- Your WHERE conditions are too restrictive
- The data doesn't exist in this trace
- You're looking in the wrong place

Please ADJUST your approach and try a different query.

Respond with ONLY one SQL query wrapped in \`\`\`sql ... \`\`\` code blocks. Do not include any explanation or additional text.`,
            user: '',
            temperature: 0.4,
        });
        // Analysis Summary Template (using centralized prompts)
        this.addTemplate({
            name: 'analysis-summary',
            system: `You are a Perfetto trace analysis expert. Provide a clear, comprehensive answer to the user based on the query results.

${prompts_1.PROMPTS.ANALYSIS_SUMMARY.detailed}

{schema}

Required output structure:
1) Executive Summary
2) Findings (each item: symptom, evidence, impact)
3) Action Items (owner, priority: P0/P1/P2, concrete action, verification steps)
4) Missing Data (what is missing + how to collect it)
5) Uncertainty (assumptions and confidence)

Rules:
- Do not make claims without evidence.
- For every finding, cite evidence as table[field]=value.
- If evidence is missing, say "unable_to_determine" and add it to Missing Data.`,
            user: `User Question: "{question}"

{context}

Provide a final answer that directly addresses the user's question. Include specific numbers and data points when relevant.`,
            temperature: 0.2,
        });
    }
    /**
     * Get a template by name
     */
    getTemplate(name) {
        return this.templates.get(name);
    }
    /**
     * Get all template names
     */
    getTemplateNames() {
        return Array.from(this.templates.keys());
    }
    /**
     * Add a new template or update existing one
     */
    addTemplate(template) {
        this.templates.set(template.name, template);
    }
    /**
     * Format a template with variables
     */
    formatTemplate(name, variables) {
        const template = this.getTemplate(name);
        if (!template) {
            throw new Error(`Template "${name}" not found`);
        }
        // Combine system and user templates
        let formatted = template.system;
        // Replace variables in both system and user parts
        for (const [key, value] of Object.entries(variables)) {
            const placeholder = `{${key}}`;
            formatted = formatted.replace(new RegExp(placeholder, 'g'), String(value));
        }
        // Add user message if it exists and isn't empty
        if (template.user && template.user.trim() !== '') {
            let userPart = template.user;
            for (const [key, value] of Object.entries(variables)) {
                const placeholder = `{${key}}`;
                userPart = userPart.replace(new RegExp(placeholder, 'g'), String(value));
            }
            formatted += '\n\n' + userPart;
        }
        return formatted;
    }
    /**
     * Get temperature for a template
     */
    getTemperature(name) {
        const template = this.getTemplate(name);
        return template?.temperature ?? 0.3;
    }
    /**
     * Check if a template exists
     */
    hasTemplate(name) {
        return this.templates.has(name);
    }
    /**
     * Remove a template
     */
    removeTemplate(name) {
        return this.templates.delete(name);
    }
}
exports.PromptTemplateService = PromptTemplateService;
// ============================================================================
// Exports
// ============================================================================
exports.default = PromptTemplateService;
//# sourceMappingURL=promptTemplateService.js.map