import { Router } from "express";
import { agentExists, getAgent } from "../services/agent-file-service.js";
import { appendActivity } from "../services/agent-activity.js";
import { listTriggers, getTrigger, createTrigger, updateTrigger, deleteTrigger } from "../services/agent-triggers.js";
import { backtestFilter } from "../services/trigger-dispatcher.js";
import { getAllEvents } from "../services/event-log.js";
import { resolveAgentKeyAlias } from "../services/agent-settings.js";
export const agentTriggersRouter = Router({ mergeParams: true });
const TIME_REGEX = /^([01]\d|2[0-3]):[0-5]\d$/;
function validateQuietHours(qh) {
    if (!qh)
        return null;
    if (typeof qh.enabled !== "boolean")
        return "quietHours.enabled must be a boolean";
    if (qh.enabled) {
        if (!TIME_REGEX.test(qh.start) || !TIME_REGEX.test(qh.end)) {
            return "quietHours start/end must be in HH:MM format (00:00 - 23:59)";
        }
    }
    return null;
}
function validateDebounce(debounce) {
    if (!debounce)
        return null;
    if (typeof debounce.enabled !== "boolean")
        return "debounce.enabled must be a boolean";
    if (debounce.enabled) {
        if (typeof debounce.windowMs !== "number" || !Number.isInteger(debounce.windowMs)) {
            return "debounce.windowMs must be an integer";
        }
        if (debounce.windowMs < 100 || debounce.windowMs > 300_000) {
            return "debounce.windowMs must be between 100 and 300000 (5 minutes)";
        }
        if (debounce.maxWaitMs != null) {
            if (typeof debounce.maxWaitMs !== "number" || !Number.isInteger(debounce.maxWaitMs)) {
                return "debounce.maxWaitMs must be an integer";
            }
            if (debounce.maxWaitMs < debounce.windowMs) {
                return "debounce.maxWaitMs must be >= debounce.windowMs";
            }
        }
    }
    return null;
}
/** GET /api/agents/:alias/triggers — list all triggers for this agent */
agentTriggersRouter.get("/", (req, res) => {
    const alias = req.params.alias;
    if (!agentExists(alias)) {
        res.status(404).json({ error: "Agent not found" });
        return;
    }
    const triggers = listTriggers(alias);
    res.json({ triggers });
});
/** POST /api/agents/:alias/triggers/backtest — test a filter against stored events */
// Must be defined BEFORE /:triggerId to avoid Express treating "backtest" as a triggerId
agentTriggersRouter.post("/backtest", (req, res) => {
    const alias = req.params.alias;
    if (!agentExists(alias)) {
        res.status(404).json({ error: "Agent not found" });
        return;
    }
    const { filter, limit } = req.body;
    if (!filter) {
        res.status(400).json({ error: "filter is required" });
        return;
    }
    // Load recent events scoped to this agent's caller alias
    const agentRaw = getAgent(alias);
    const agent = agentRaw ? resolveAgentKeyAlias(agentRaw) : undefined;
    const callerAlias = agent?.mcpKeyAlias;
    const allEvents = callerAlias ? getAllEvents(callerAlias, { limit: limit || 500 }) : [];
    const matches = backtestFilter(allEvents, filter);
    res.json({
        totalScanned: allEvents.length,
        matchCount: matches.length,
        matches: matches.slice(0, 50), // Cap response size
    });
});
/** GET /api/agents/:alias/triggers/:triggerId — get a single trigger */
agentTriggersRouter.get("/:triggerId", (req, res) => {
    const alias = req.params.alias;
    const triggerId = req.params.triggerId;
    if (!agentExists(alias)) {
        res.status(404).json({ error: "Agent not found" });
        return;
    }
    const trigger = getTrigger(alias, triggerId);
    if (!trigger) {
        res.status(404).json({ error: "Trigger not found" });
        return;
    }
    res.json({ trigger });
});
/** POST /api/agents/:alias/triggers — create a new trigger */
agentTriggersRouter.post("/", (req, res) => {
    const alias = req.params.alias;
    if (!agentExists(alias)) {
        res.status(404).json({ error: "Agent not found" });
        return;
    }
    const { name, description, filter, action, status, quietHours, debounce } = req.body;
    if (!name || !filter) {
        res.status(400).json({ error: "name and filter are required" });
        return;
    }
    const qhError = validateQuietHours(quietHours);
    if (qhError) {
        res.status(400).json({ error: qhError });
        return;
    }
    const dbError = validateDebounce(debounce);
    if (dbError) {
        res.status(400).json({ error: dbError });
        return;
    }
    const cronAction = action || { type: "start_session" };
    const trigger = createTrigger(alias, {
        name: name.trim(),
        description: (description || "").trim(),
        status: status || "active",
        filter,
        action: cronAction,
        triggerCount: 0,
        ...(quietHours && { quietHours }),
        ...(debounce && { debounce }),
    });
    appendActivity(alias, {
        type: "trigger",
        message: `Trigger "${trigger.name}" created`,
        metadata: { triggerId: trigger.id, action: "created" },
    });
    res.status(201).json({ trigger });
});
/** PUT /api/agents/:alias/triggers/:triggerId — update a trigger */
agentTriggersRouter.put("/:triggerId", (req, res) => {
    const alias = req.params.alias;
    const triggerId = req.params.triggerId;
    if (!agentExists(alias)) {
        res.status(404).json({ error: "Agent not found" });
        return;
    }
    const updates = req.body;
    const qhError = validateQuietHours(updates.quietHours);
    if (qhError) {
        res.status(400).json({ error: qhError });
        return;
    }
    const dbError = validateDebounce(updates.debounce);
    if (dbError) {
        res.status(400).json({ error: dbError });
        return;
    }
    const trigger = updateTrigger(alias, triggerId, updates);
    if (!trigger) {
        res.status(404).json({ error: "Trigger not found" });
        return;
    }
    appendActivity(alias, {
        type: "trigger",
        message: `Trigger "${trigger.name}" updated`,
        metadata: { triggerId: trigger.id, action: "updated" },
    });
    res.json({ trigger });
});
/** DELETE /api/agents/:alias/triggers/:triggerId — delete a trigger */
agentTriggersRouter.delete("/:triggerId", (req, res) => {
    const alias = req.params.alias;
    const triggerId = req.params.triggerId;
    if (!agentExists(alias)) {
        res.status(404).json({ error: "Agent not found" });
        return;
    }
    const existing = getTrigger(alias, triggerId);
    const deleted = deleteTrigger(alias, triggerId);
    if (!deleted) {
        res.status(404).json({ error: "Trigger not found" });
        return;
    }
    appendActivity(alias, {
        type: "trigger",
        message: `Trigger "${existing?.name || triggerId}" deleted`,
        metadata: { triggerId, action: "deleted" },
    });
    res.json({ ok: true });
});
