/**
 * jait — Platform meta-tool for Jait-specific capabilities.
 *
 * Combines: memory management, cron/scheduler, network scanning,
 * and gateway status into a single tool with an `action` dispatcher.
 *
 * This keeps the core tool count at 8 while still exposing
 * platform-specific features that don't fit the generic tools.
 */
export function createJaitTool(deps) {
    return {
        name: "jait",
        description: "Jait platform tool — access memory, scheduler, and gateway status. " +
            "Actions: memory.save, memory.search, memory.forget, reminder.save, reminder.list, reminder.update, reminder.forget, cron.add, cron.list, cron.update, cron.remove, status.",
        tier: "core",
        category: "gateway",
        source: "builtin",
        parameters: {
            type: "object",
            properties: {
                action: {
                    type: "string",
                    description: "Action to perform.",
                    enum: [
                        "memory.save", "memory.search", "memory.forget",
                        "reminder.save", "reminder.list", "reminder.update", "reminder.forget",
                        "cron.add", "cron.list", "cron.update", "cron.remove",
                        "status",
                    ],
                },
                // Memory params
                content: {
                    type: "string",
                    description: "Content to save.",
                },
                scope: {
                    type: "string",
                    description: "Memory scope.",
                    enum: ["project", "contact"],
                },
                query: {
                    type: "string",
                    description: "Search query.",
                },
                memoryId: {
                    type: "string",
                    description: "Memory ID to forget.",
                },
                sourceType: {
                    type: "string",
                    description: "Source type.",
                },
                sourceId: {
                    type: "string",
                    description: "Source ID (for memory.save).",
                },
                ttlSeconds: {
                    type: "number",
                    description: "TTL in seconds for memory expiry (for memory.save).",
                },
                limit: {
                    type: "number",
                    description: "Max results (for memory.search, default: 5).",
                },
                asReminder: {
                    type: "boolean",
                    description: "For memory.save, save content to the reminders table instead of semantic memory.",
                },
                projectId: {
                    type: "string",
                    description: "Project ID for reminder actions.",
                },
                reminderId: {
                    type: "string",
                    description: "Reminder ID to forget.",
                },
                tags: {
                    type: "array",
                    items: { type: "string" },
                    description: "Reminder tags.",
                },
                status: {
                    type: "string",
                    enum: ["active", "archived", "all"],
                    description: "Reminder status for list/update.",
                },
                sessionId: {
                    type: "string",
                    description: "Session ID for reminder actions.",
                },
                // Cron params
                name: {
                    type: "string",
                    description: "Cron job name (for cron.add).",
                },
                cron: {
                    type: "string",
                    description: 'Cron expression (for cron.add/update). E.g. "0 9 * * *" for daily at 9am.',
                },
                toolName: {
                    type: "string",
                    description: "Tool name to execute on schedule (for cron.add).",
                },
                input: {
                    type: "object",
                    description: "Tool input arguments (for cron.add/update).",
                },
                jobId: {
                    type: "string",
                    description: "Cron job ID (for cron.update/remove).",
                },
                enabled: {
                    type: "boolean",
                    description: "Enable/disable toggle (for cron.update).",
                },
            },
            required: ["action"],
        },
        async execute(input, context) {
            try {
                switch (input.action) {
                    // ── Memory ──────────────────────────────────────────────
                    case "memory.save": {
                        if (input.asReminder) {
                            if (!deps.reminderService) {
                                return { ok: false, message: "Reminder service not available." };
                            }
                            if (!input.content) {
                                return { ok: false, message: "memory.save with asReminder requires `content`." };
                            }
                            const reminder = deps.reminderService.create({
                                userId: context.userId,
                                projectId: input.projectId ?? null,
                                sessionId: input.sessionId ?? context.sessionId,
                                content: input.content,
                                sourceType: input.sourceType ?? "agent",
                                sourceId: input.sourceId ?? context.actionId,
                                sourceSurface: "chat",
                                tags: input.tags,
                            });
                            return { ok: true, message: `Saved reminder ${reminder.id}`, data: reminder };
                        }
                        if (!deps.memoryService) {
                            return { ok: false, message: "Memory service not available." };
                        }
                        if (!input.content) {
                            return { ok: false, message: "memory.save requires `content`." };
                        }
                        const expiresAt = input.ttlSeconds
                            ? new Date(Date.now() + input.ttlSeconds * 1000).toISOString()
                            : undefined;
                        const entry = await deps.memoryService.save({
                            scope: input.scope ?? "project",
                            content: input.content,
                            source: {
                                type: input.sourceType ?? "agent",
                                id: input.sourceId ?? context.actionId,
                                surface: "chat",
                            },
                            expiresAt,
                        });
                        return { ok: true, message: `Saved memory ${entry.id}`, data: entry };
                    }
                    case "reminder.save": {
                        if (!deps.reminderService) {
                            return { ok: false, message: "Reminder service not available." };
                        }
                        if (!input.content) {
                            return { ok: false, message: "reminder.save requires `content`." };
                        }
                        const reminder = deps.reminderService.create({
                            userId: context.userId,
                            projectId: input.projectId ?? null,
                            sessionId: input.sessionId ?? context.sessionId,
                            content: input.content,
                            sourceType: input.sourceType ?? "agent",
                            sourceId: input.sourceId ?? context.actionId,
                            sourceSurface: "chat",
                            tags: input.tags,
                        });
                        return { ok: true, message: `Saved reminder ${reminder.id}`, data: reminder };
                    }
                    case "memory.search": {
                        if (!deps.memoryService) {
                            return { ok: false, message: "Memory service not available." };
                        }
                        if (!input.query) {
                            return { ok: false, message: "memory.search requires `query`." };
                        }
                        const results = await deps.memoryService.search(input.query, input.limit ?? 5, input.scope);
                        const reminders = deps.reminderService?.list({
                            userId: context.userId,
                            status: "active",
                            limit: input.limit ?? 5,
                        }) ?? [];
                        return {
                            ok: true,
                            message: `Found ${results.length} memories and ${reminders.length} reminders`,
                            data: { memories: results, reminders },
                        };
                    }
                    case "reminder.list": {
                        if (!deps.reminderService) {
                            return { ok: false, message: "Reminder service not available." };
                        }
                        const reminders = deps.reminderService.list({
                            userId: context.userId,
                            projectId: input.projectId ?? undefined,
                            status: input.status === "archived" || input.status === "all" ? input.status : "active",
                            sessionId: input.sessionId ?? undefined,
                            limit: input.limit ?? 50,
                        });
                        return { ok: true, message: `Loaded ${reminders.length} reminders`, data: { reminders } };
                    }
                    case "reminder.update": {
                        if (!deps.reminderService) {
                            return { ok: false, message: "Reminder service not available." };
                        }
                        const id = input.reminderId ?? input.memoryId;
                        if (!id) {
                            return { ok: false, message: "reminder.update requires `reminderId`." };
                        }
                        const status = input.status === undefined
                            ? undefined
                            : input.status === "active" || input.status === "archived"
                                ? input.status
                                : null;
                        if (status === null) {
                            return { ok: false, message: "reminder.update status must be active or archived." };
                        }
                        const reminder = deps.reminderService.update(id, {
                            content: input.content,
                            projectId: input.projectId,
                            sessionId: input.sessionId,
                            status,
                            tags: input.tags,
                        }, context.userId);
                        return {
                            ok: !!reminder,
                            message: reminder ? `Updated reminder ${id}` : `Reminder ${id} not found`,
                            data: reminder,
                        };
                    }
                    case "memory.forget": {
                        if (deps.reminderService && input.memoryId) {
                            const removedReminder = deps.reminderService.delete(input.memoryId, context.userId);
                            if (removedReminder) {
                                return { ok: true, message: `Forgot reminder ${input.memoryId}` };
                            }
                        }
                        if (!deps.memoryService) {
                            return { ok: false, message: "Memory service not available." };
                        }
                        if (!input.memoryId) {
                            return { ok: false, message: "memory.forget requires `memoryId`." };
                        }
                        const removed = await deps.memoryService.forget(input.memoryId);
                        return {
                            ok: removed,
                            message: removed ? `Forgot memory ${input.memoryId}` : `Memory ${input.memoryId} not found`,
                        };
                    }
                    case "reminder.forget": {
                        if (!deps.reminderService) {
                            return { ok: false, message: "Reminder service not available." };
                        }
                        const id = input.reminderId ?? input.memoryId;
                        if (!id) {
                            return { ok: false, message: "reminder.forget requires `reminderId`." };
                        }
                        const removed = deps.reminderService.delete(id, context.userId);
                        return {
                            ok: removed,
                            message: removed ? `Forgot reminder ${id}` : `Reminder ${id} not found`,
                        };
                    }
                    // ── Cron ────────────────────────────────────────────────
                    case "cron.add": {
                        if (!deps.scheduler) {
                            return { ok: false, message: "Scheduler not available." };
                        }
                        if (!input.name || !input.cron || !input.toolName) {
                            return { ok: false, message: "cron.add requires `name`, `cron`, and `toolName`." };
                        }
                        // Normalize tool name (underscore → dot)
                        const toolNameNormalized = input.toolName.includes("_") && !input.toolName.includes(".")
                            ? input.toolName.replace("_", ".")
                            : input.toolName;
                        const job = deps.scheduler.create({
                            userId: context.userId,
                            name: input.name,
                            cron: input.cron,
                            toolName: toolNameNormalized,
                            input: input.input ?? {},
                            sessionId: context.sessionId,
                            projectRoot: process.cwd(),
                        });
                        return { ok: true, message: "Cron job created", data: job };
                    }
                    case "cron.list": {
                        if (!deps.scheduler) {
                            return { ok: false, message: "Scheduler not available." };
                        }
                        const jobs = deps.scheduler.list(context.userId);
                        return { ok: true, message: `${jobs.length} cron jobs`, data: { jobs } };
                    }
                    case "cron.update": {
                        if (!deps.scheduler) {
                            return { ok: false, message: "Scheduler not available." };
                        }
                        if (!input.jobId) {
                            return { ok: false, message: "cron.update requires `jobId`." };
                        }
                        const updated = deps.scheduler.update(input.jobId, {
                            name: input.name,
                            cron: input.cron,
                            enabled: input.enabled,
                            input: input.input,
                        }, context.userId);
                        return {
                            ok: !!updated,
                            message: updated ? "Cron job updated" : "Cron job not found",
                            data: updated ?? { id: input.jobId },
                        };
                    }
                    case "cron.remove": {
                        if (!deps.scheduler) {
                            return { ok: false, message: "Scheduler not available." };
                        }
                        if (!input.jobId) {
                            return { ok: false, message: "cron.remove requires `jobId`." };
                        }
                        const removed = deps.scheduler.remove(input.jobId, context.userId);
                        return {
                            ok: removed,
                            message: removed ? "Cron job removed" : "Cron job not found",
                        };
                    }
                    // ── Gateway status ──────────────────────────────────────
                    case "status": {
                        const sessions = deps.sessionService?.list("active").length ?? 0;
                        const surfaces = deps.surfaceRegistry?.listSurfaces().length ?? 0;
                        const devices = deps.ws?.clientCount ?? 0;
                        const jobs = deps.scheduler?.list() ?? [];
                        const enabledJobs = jobs.filter((j) => j.enabled).length;
                        const hookEventTypes = deps.hooks?.registeredEventTypes() ?? [];
                        return {
                            ok: true,
                            message: "Gateway status",
                            data: {
                                healthy: true,
                                uptime: Math.floor((Date.now() - (deps.startedAt ?? Date.now())) / 1000),
                                sessions,
                                surfaces,
                                devices,
                                scheduler: { totalJobs: jobs.length, enabledJobs },
                                hooks: {
                                    registeredEventTypes: hookEventTypes,
                                    listeners: deps.hooks?.listenerCount() ?? 0,
                                },
                            },
                        };
                    }
                    default:
                        return {
                            ok: false,
                            message: `Unknown action: "${input.action}". ` +
                                "Valid actions: memory.save, memory.search, memory.forget, reminder.save, reminder.list, reminder.update, reminder.forget, " +
                                "cron.add, cron.list, cron.update, cron.remove, status.",
                        };
                }
            }
            catch (err) {
                return {
                    ok: false,
                    message: err instanceof Error ? err.message : "Jait tool failed",
                };
            }
        },
    };
}
//# sourceMappingURL=jait.js.map