import * as fs from 'fs';
import * as path from 'path';
import { randomUUID } from 'crypto';
export class HookEventRouter {
    constructor(store, projectRoot) {
        this.store = store;
        this.projectRoot = projectRoot;
        this.handlers = new Map();
        this.logPath = path.join(projectRoot, '.specweave', 'logs', 'hooks.log');
    }
    register(eventName, handler) {
        this.handlers.set(eventName, handler);
    }
    async handle(eventName, body) {
        const handler = this.handlers.get(eventName);
        if (!handler) {
            return { status: 400, body: { error: `Unknown event type: ${eventName}` } };
        }
        const sessionId = (body && typeof body === 'object' && 'sessionId' in body)
            ? String(body.sessionId)
            : 'unknown';
        const payload = { eventName, body, sessionId };
        const start = Date.now();
        try {
            const result = await handler(payload);
            const durationMs = Date.now() - start;
            const event = {
                id: randomUUID(),
                eventName: eventName,
                sessionId,
                timestamp: new Date().toISOString(),
                payload: body,
                durationMs,
                result: (() => {
                    if (!result.body || typeof result.body !== 'object')
                        return undefined;
                    const hso = result.body.hookSpecificOutput;
                    if (!hso)
                        return undefined;
                    const decision = hso.permissionDecision;
                    if (!decision)
                        return undefined;
                    return { decision: decision, reason: hso.permissionDecisionReason ?? undefined };
                })(),
            };
            this.store.addEvent(event);
            return { ...result, storedEvent: event };
        }
        catch (err) {
            const durationMs = Date.now() - start;
            this.appendLog(eventName, err);
            const event = {
                id: randomUUID(),
                eventName: eventName,
                sessionId,
                timestamp: new Date().toISOString(),
                payload: body,
                durationMs,
            };
            this.store.addEvent(event);
            return { status: 200, body: {}, storedEvent: event };
        }
    }
    appendLog(eventName, err) {
        try {
            const logDir = path.dirname(this.logPath);
            fs.mkdirSync(logDir, { recursive: true });
            const message = err instanceof Error ? err.message : String(err);
            const line = `[${new Date().toISOString()}] [${eventName}] ERROR: ${message}\n`;
            fs.appendFileSync(this.logPath, line);
        }
        catch {
            // Logging failure must never propagate
        }
    }
}
//# sourceMappingURL=hook-event-router.js.map