/**
 * Trigger Registry
 *
 * CRUD operations for triggers with persistence to ~/.codebuddy/triggers.json.
 * Includes predefined trigger templates.
 */
import * as fs from 'fs/promises';
import * as path from 'path';
import { homedir } from 'os';
import * as crypto from 'crypto';
import { logger } from '../../utils/logger.js';
const TRIGGERS_FILE = path.join(homedir(), '.codebuddy', 'triggers.json');
// Predefined trigger templates
export const TRIGGER_TEMPLATES = {
    'file-change-notify': {
        name: 'File Change Notification',
        type: 'file_change',
        condition: 'src/**/*.ts',
        action: { type: 'notify', target: 'cli' },
        cooldownMs: 5000,
        enabled: true,
    },
    'screen-change-alert': {
        name: 'Screen Change Alert',
        type: 'screen_change',
        condition: '0.5',
        action: { type: 'notify', target: 'cli' },
        cooldownMs: 10000,
        enabled: true,
    },
    'webhook-handler': {
        name: 'Webhook Handler',
        type: 'webhook',
        condition: '*',
        action: { type: 'agent_message', target: 'Process incoming webhook' },
        cooldownMs: 1000,
        enabled: true,
    },
};
export class TriggerRegistry {
    triggerManager;
    constructor(triggerManager) {
        this.triggerManager = triggerManager;
    }
    /**
     * Load triggers from disk
     */
    async load() {
        try {
            const data = await fs.readFile(TRIGGERS_FILE, 'utf-8');
            const triggers = JSON.parse(data);
            for (const trigger of triggers) {
                trigger.createdAt = new Date(trigger.createdAt);
                if (trigger.lastFiredAt)
                    trigger.lastFiredAt = new Date(trigger.lastFiredAt);
                this.triggerManager.addTrigger(trigger);
            }
            logger.debug(`Loaded ${triggers.length} triggers`);
        }
        catch {
            // No triggers file yet
        }
    }
    /**
     * Save triggers to disk
     */
    async save() {
        try {
            await fs.mkdir(path.dirname(TRIGGERS_FILE), { recursive: true });
            const triggers = this.triggerManager.listTriggers();
            await fs.writeFile(TRIGGERS_FILE, JSON.stringify(triggers, null, 2));
        }
        catch (error) {
            logger.warn('Failed to save triggers', { error: String(error) });
        }
    }
    /**
     * Create a new trigger
     */
    async create(params) {
        const trigger = {
            id: crypto.randomUUID(),
            name: params.name,
            type: params.type,
            condition: params.condition,
            action: params.action,
            cooldownMs: params.cooldownMs || 5000,
            enabled: true,
            createdAt: new Date(),
            fireCount: 0,
        };
        this.triggerManager.addTrigger(trigger);
        await this.save();
        return trigger;
    }
    /**
     * Create from template
     */
    async createFromTemplate(templateId) {
        const template = TRIGGER_TEMPLATES[templateId];
        if (!template)
            return null;
        return this.create({
            name: template.name,
            type: template.type,
            condition: template.condition,
            action: template.action,
            cooldownMs: template.cooldownMs,
        });
    }
    /**
     * Delete a trigger
     */
    async delete(id) {
        const removed = this.triggerManager.removeTrigger(id);
        if (removed)
            await this.save();
        return removed;
    }
    /**
     * List templates
     */
    listTemplates() {
        return Object.keys(TRIGGER_TEMPLATES);
    }
}
//# sourceMappingURL=trigger-registry.js.map