"use strict";
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.config = exports.ConfigManager = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
class ConfigManager {
    static instance;
    configDir;
    preferencesPath;
    registryPath;
    cacheDir;
    constructor() {
        // Store in user's home directory for persistence across updates
        this.configDir = path.join(os.homedir(), '.opencode-agency');
        this.preferencesPath = path.join(this.configDir, 'preferences.json');
        this.registryPath = path.join(this.configDir, 'agent-registry.json');
        this.cacheDir = path.join(this.configDir, 'cache');
        this.ensureDirectories();
    }
    static getInstance() {
        if (!ConfigManager.instance) {
            ConfigManager.instance = new ConfigManager();
        }
        return ConfigManager.instance;
    }
    ensureDirectories() {
        if (!fs.existsSync(this.configDir)) {
            fs.mkdirSync(this.configDir, { recursive: true });
        }
        if (!fs.existsSync(this.cacheDir)) {
            fs.mkdirSync(this.cacheDir, { recursive: true });
        }
    }
    /**
     * Get user preferences
     */
    getPreferences() {
        if (fs.existsSync(this.preferencesPath)) {
            try {
                const data = fs.readFileSync(this.preferencesPath, 'utf-8');
                return JSON.parse(data);
            }
            catch (error) {
                console.error('Error reading preferences:', error);
                return this.getDefaultPreferences();
            }
        }
        return this.getDefaultPreferences();
    }
    /**
     * Save user preferences
     */
    savePreferences(preferences) {
        fs.writeFileSync(this.preferencesPath, JSON.stringify(preferences, null, 2), 'utf-8');
    }
    /**
     * Update a specific preference
     */
    updatePreference(key, value) {
        const preferences = this.getPreferences();
        preferences[key] = value;
        this.savePreferences(preferences);
    }
    /**
     * Learn from user override
     */
    learnOverride(pattern, agent, confidence) {
        const preferences = this.getPreferences();
        // Add to routing overrides
        preferences.routingOverrides.push({
            pattern: pattern.toLowerCase(),
            agent,
            timestamp: new Date().toISOString(),
            confidence
        });
        // Keep only last 100 overrides
        if (preferences.routingOverrides.length > 100) {
            preferences.routingOverrides = preferences.routingOverrides.slice(-100);
        }
        // Update preferred agent for task type
        const taskType = this.inferTaskType(pattern);
        preferences.preferredAgents[taskType] = agent;
        this.savePreferences(preferences);
    }
    /**
     * Check if user has preferred agent for task
     */
    getPreferredAgent(task) {
        const preferences = this.getPreferences();
        const taskType = this.inferTaskType(task);
        // Check exact pattern match first
        const exactMatch = preferences.routingOverrides.find(o => o.pattern === task.toLowerCase());
        if (exactMatch) {
            return exactMatch.agent;
        }
        // Check task type preference
        if (preferences.preferredAgents[taskType]) {
            return preferences.preferredAgents[taskType];
        }
        return null;
    }
    /**
     * Record clarification interaction
     */
    recordClarification(prompt, questions, answers) {
        const preferences = this.getPreferences();
        preferences.clarificationHistory.push({
            prompt: prompt.toLowerCase(),
            questions,
            answers,
            timestamp: new Date().toISOString()
        });
        // Keep only last 50 clarifications
        if (preferences.clarificationHistory.length > 50) {
            preferences.clarificationHistory = preferences.clarificationHistory.slice(-50);
        }
        this.savePreferences(preferences);
    }
    /**
     * Get similar past clarifications
     */
    getSimilarClarifications(prompt) {
        const preferences = this.getPreferences();
        const promptWords = prompt.toLowerCase().split(/\s+/);
        return preferences.clarificationHistory
            .filter(c => {
            const overlap = c.prompt.split(/\s+/).filter(word => promptWords.includes(word)).length;
            return overlap > 1; // At least 2 words overlap
        })
            .slice(-5) // Last 5 similar
            .map(c => ({
            questions: c.questions,
            answers: c.answers
        }));
    }
    /**
     * Get default tech stack from history
     */
    getDefaultStack() {
        const preferences = this.getPreferences();
        if (preferences.techStackHistory.length === 0) {
            return preferences.defaultStack;
        }
        // Find most frequently used stack
        const stackCounts = {};
        preferences.techStackHistory.forEach(h => {
            stackCounts[h.stack] = (stackCounts[h.stack] || 0) + 1;
        });
        const mostUsed = Object.entries(stackCounts)
            .sort(([, a], [, b]) => b - a)[0];
        return mostUsed ? mostUsed[0] : preferences.defaultStack;
    }
    /**
     * Record tech stack choice
     */
    recordStackChoice(project, stack) {
        const preferences = this.getPreferences();
        preferences.techStackHistory.push({
            project,
            stack,
            timestamp: new Date().toISOString()
        });
        // Keep only last 20
        if (preferences.techStackHistory.length > 20) {
            preferences.techStackHistory = preferences.techStackHistory.slice(-20);
        }
        // Update default
        preferences.defaultStack = stack;
        this.savePreferences(preferences);
    }
    /**
     * Get agent registry (cached or fresh)
     */
    getAgentRegistry() {
        if (fs.existsSync(this.registryPath)) {
            try {
                const data = fs.readFileSync(this.registryPath, 'utf-8');
                return JSON.parse(data);
            }
            catch (error) {
                console.error('Error reading registry:', error);
            }
        }
        return this.getDefaultRegistry();
    }
    /**
     * Update agent registry
     */
    updateRegistry(registry) {
        fs.writeFileSync(this.registryPath, JSON.stringify(registry, null, 2), 'utf-8');
    }
    /**
     * Check for agent updates
     */
    checkForUpdates() {
        const registry = this.getAgentRegistry();
        const agentsDir = path.join(process.cwd(), '.opencode', 'agents');
        if (!fs.existsSync(agentsDir)) {
            return { hasUpdates: false, outdatedAgents: [] };
        }
        const outdatedAgents = [];
        for (const agent of registry.agents) {
            const agentPath = path.join(agentsDir, `${agent.name}.md`);
            if (!fs.existsSync(agentPath)) {
                outdatedAgents.push(agent.name);
                continue;
            }
            const stats = fs.statSync(agentPath);
            const lastModified = stats.mtime.toISOString();
            if (new Date(lastModified) > new Date(agent.lastUpdated)) {
                outdatedAgents.push(agent.name);
            }
        }
        return {
            hasUpdates: outdatedAgents.length > 0,
            outdatedAgents
        };
    }
    /**
     * Export all user data
     */
    exportData() {
        return JSON.stringify({
            preferences: this.getPreferences(),
            registry: this.getAgentRegistry(),
            exportedAt: new Date().toISOString()
        }, null, 2);
    }
    /**
     * Import user data
     */
    importData(data) {
        const parsed = JSON.parse(data);
        if (parsed.preferences) {
            this.savePreferences(parsed.preferences);
        }
        if (parsed.registry) {
            this.updateRegistry(parsed.registry);
        }
    }
    /**
     * Reset all preferences
     */
    reset() {
        const defaultPrefs = this.getDefaultPreferences();
        this.savePreferences(defaultPrefs);
        if (fs.existsSync(this.registryPath)) {
            fs.unlinkSync(this.registryPath);
        }
    }
    /**
     * Get default preferences
     */
    getDefaultPreferences() {
        return {
            defaultStack: 'nextjs',
            preferredAgents: {
                frontend: '@frontend-developer',
                backend: '@backend-architect',
                api: '@api-architect',
                testing: '@testing-reality-checker',
                devops: '@devops-automator',
                general: '@orchestrator'
            },
            routingOverrides: [],
            techStackHistory: [],
            clarificationHistory: [],
            theme: 'dark',
            autoConfirm: false,
            confidenceThreshold: 70
        };
    }
    /**
     * Get default registry
     */
    getDefaultRegistry() {
        return {
            agents: [],
            workflows: []
        };
    }
    /**
     * Infer task type from prompt
     */
    inferTaskType(prompt) {
        const p = prompt.toLowerCase();
        if (p.includes('api') || p.includes('endpoint') || p.includes('rest') || p.includes('graphql')) {
            return 'api';
        }
        if (p.includes('frontend') || p.includes('ui') || p.includes('component') || p.includes('react') || p.includes('vue')) {
            return 'frontend';
        }
        if (p.includes('backend') || p.includes('server') || p.includes('database')) {
            return 'backend';
        }
        if (p.includes('test') || p.includes('bug') || p.includes('debug')) {
            return 'testing';
        }
        if (p.includes('deploy') || p.includes('docker') || p.includes('ci/cd')) {
            return 'devops';
        }
        if (p.includes('design') || p.includes('color') || p.includes('style')) {
            return 'design';
        }
        return 'general';
    }
}
exports.ConfigManager = ConfigManager;
// Export singleton
exports.config = ConfigManager.getInstance();
//# sourceMappingURL=config-manager.js.map