"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 __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.expertRegistry = exports.createSystemExpert = exports.SystemExpert = exports.createLaunchExpert = exports.LaunchExpert = exports.createInteractionExpert = exports.InteractionExpert = void 0;
exports.initializeExperts = initializeExperts;
exports.getExpertForIntent = getExpertForIntent;
exports.parseAnalysisIntent = parseAnalysisIntent;
/**
 * Expert System Module
 *
 * Exports all domain experts and the expert registry for
 * intelligent, domain-specific performance analysis.
 *
 * The expert system provides:
 * - Domain-specific analysis strategies
 * - Architecture-aware decision trees
 * - Intent-based routing
 * - Root cause classification
 *
 * Cross-Domain Expert System (New):
 * - Module Experts (YAML Skills) provide specialized data analysis
 * - Cross-Domain Experts (TypeScript) orchestrate multi-turn dialogues
 * - Hypothesis management for root cause verification
 */
// Base types and class
__exportStar(require("./base"), exports);
// Cross-Domain Expert System
__exportStar(require("./crossDomain"), exports);
// Domain experts
var interactionExpert_1 = require("./interactionExpert");
Object.defineProperty(exports, "InteractionExpert", { enumerable: true, get: function () { return interactionExpert_1.InteractionExpert; } });
Object.defineProperty(exports, "createInteractionExpert", { enumerable: true, get: function () { return interactionExpert_1.createInteractionExpert; } });
var launchExpert_1 = require("./launchExpert");
Object.defineProperty(exports, "LaunchExpert", { enumerable: true, get: function () { return launchExpert_1.LaunchExpert; } });
Object.defineProperty(exports, "createLaunchExpert", { enumerable: true, get: function () { return launchExpert_1.createLaunchExpert; } });
var systemExpert_1 = require("./systemExpert");
Object.defineProperty(exports, "SystemExpert", { enumerable: true, get: function () { return systemExpert_1.SystemExpert; } });
Object.defineProperty(exports, "createSystemExpert", { enumerable: true, get: function () { return systemExpert_1.createSystemExpert; } });
const interactionExpert_2 = require("./interactionExpert");
const launchExpert_2 = require("./launchExpert");
const systemExpert_2 = require("./systemExpert");
/**
 * Expert Registry Implementation
 *
 * Manages registration and lookup of domain experts.
 * Supports intent-based routing to find the appropriate expert.
 */
class ExpertRegistryImpl {
    constructor() {
        this.experts = new Map();
        this.intentToExpert = new Map();
    }
    /**
     * Register an expert
     */
    register(expert) {
        this.experts.set(expert.config.id, expert);
        // Build intent mapping
        for (const intent of expert.config.handlesIntents) {
            this.intentToExpert.set(intent, expert.config.id);
        }
        console.log(`[ExpertRegistry] Registered expert: ${expert.config.name} (${expert.config.id})`);
    }
    /**
     * Get expert by ID
     */
    get(expertId) {
        return this.experts.get(expertId);
    }
    /**
     * Get expert for a specific intent
     */
    getForIntent(intent) {
        const expertId = this.intentToExpert.get(intent.category);
        if (expertId) {
            return this.experts.get(expertId);
        }
        return undefined;
    }
    /**
     * List all registered experts
     */
    list() {
        return Array.from(this.experts.values()).map((e) => e.config);
    }
    /**
     * Check if an expert exists for the given intent
     */
    hasExpertFor(intentCategory) {
        return this.intentToExpert.has(intentCategory);
    }
    /**
     * Get all supported intent categories
     */
    getSupportedIntents() {
        return Array.from(this.intentToExpert.keys());
    }
}
/**
 * Global expert registry instance
 */
exports.expertRegistry = new ExpertRegistryImpl();
/**
 * Initialize the expert registry with all domain experts
 */
function initializeExperts() {
    // Create and register all experts
    exports.expertRegistry.register((0, interactionExpert_2.createInteractionExpert)());
    exports.expertRegistry.register((0, launchExpert_2.createLaunchExpert)());
    exports.expertRegistry.register((0, systemExpert_2.createSystemExpert)());
    console.log(`[ExpertRegistry] Initialized ${exports.expertRegistry.list().length} experts`);
    console.log(`[ExpertRegistry] Supported intents: ${exports.expertRegistry.getSupportedIntents().join(', ')}`);
}
/**
 * Get the appropriate expert for an intent
 */
function getExpertForIntent(intent) {
    return exports.expertRegistry.getForIntent(intent);
}
/**
 * Parse user query to determine analysis intent
 *
 * This is a simple keyword-based intent classifier.
 * In production, this could be enhanced with NLP or LLM.
 */
function parseAnalysisIntent(query) {
    const lowerQuery = query.toLowerCase();
    const keywords = [];
    // First check for high-priority compound phrases that should override simple keywords
    // These are checked first because they contain ambiguous substrings
    const priorityPatterns = [
        {
            category: 'ANR',
            phrases: ['anr', '无响应', 'not responding', '卡死', '死锁', 'deadlock', 'application not responding'],
        },
    ];
    // Check priority patterns first
    for (const pattern of priorityPatterns) {
        for (const phrase of pattern.phrases) {
            if (lowerQuery.includes(phrase)) {
                keywords.push(phrase);
                return {
                    category: pattern.category,
                    originalQuery: query,
                    keywords: [...new Set(keywords)],
                    confidence: Math.min(1, keywords.length / 2),
                };
            }
        }
    }
    // Define keyword patterns for each category
    const patterns = [
        {
            category: 'SCROLLING',
            keywords: ['滑动', '卡顿', 'scroll', 'jank', 'fps', '掉帧', '流畅', 'frame', '帧'],
        },
        {
            category: 'CLICK',
            keywords: ['点击', '响应', 'click', 'tap', 'touch', '交互', '反应慢'],
        },
        {
            category: 'LAUNCH',
            keywords: ['启动', 'launch', 'startup', 'start', '冷启动', '热启动', '温启动', 'ttid', 'ttfd'],
        },
        {
            category: 'CPU',
            keywords: ['cpu', '处理器', '计算', '频率', '调度', 'scheduling', '负载'],
        },
        {
            category: 'MEMORY',
            keywords: ['memory', '内存', 'gc', '垃圾回收', '内存泄漏', 'leak', '堆'],
        },
        {
            category: 'IO',
            keywords: ['io', '磁盘', 'disk', '文件', '网络', 'network', '阻塞', 'blocking'],
        },
        {
            category: 'ANR',
            keywords: ['anr'], // Main ANR keywords handled above in priority patterns
        },
    ];
    // Find matching category
    let bestMatch = {
        category: 'GENERAL',
        score: 0,
    };
    for (const pattern of patterns) {
        let score = 0;
        for (const keyword of pattern.keywords) {
            if (lowerQuery.includes(keyword)) {
                score++;
                keywords.push(keyword);
            }
        }
        if (score > bestMatch.score) {
            bestMatch = { category: pattern.category, score };
        }
    }
    return {
        category: bestMatch.category,
        originalQuery: query,
        keywords: [...new Set(keywords)], // Deduplicate
        confidence: Math.min(1, bestMatch.score / 3), // Normalize confidence
    };
}
//# sourceMappingURL=index.js.map