// Saeeol-specific routes that live in the CLI package (direct access to internals).
// All future saeeol-specific endpoints should be added here.
import { Hono } from "hono"
import { describeRoute, validator, resolver } from "hono-openapi"
import z from "zod"
import { Skill } from "@/skill"
import { Agent } from "@/agent/agent"
import { lazy } from "@/util/lazy"
import { errors } from "../../error"
import { SessionImportRoutes } from "@/saeeol/session-import/routes"
import { HeapSnapshot } from "@/saeeol/cli/heap-snapshot"

export const SaeeolRoutes = lazy(() =>
  new Hono()
    .route("/session-import", SessionImportRoutes())
    .post(
      "/heap/snapshot",
      describeRoute({
        summary: "Write heap snapshot",
        description: "Write a heap snapshot for the CLI process to the log directory.",
        operationId: "saeeol.heap.snapshot",
        responses: {
          200: {
            description: "Heap snapshot file path",
            content: {
              "application/json": {
                schema: resolver(z.string()),
              },
            },
          },
          ...errors(400),
        },
      }),
      async (c) => {
        return c.json(HeapSnapshot.write())
      },
    )
    .post(
      "/skill/remove",
      describeRoute({
        summary: "Remove a skill",
        description: "Remove a skill by deleting its directory from disk and clearing it from cache.",
        operationId: "saeeol.removeSkill",
        responses: {
          200: {
            description: "Skill removed",
            content: {
              "application/json": {
                schema: resolver(z.boolean()),
              },
            },
          },
          ...errors(400),
        },
      }),
      validator(
        "json",
        z.object({
          location: z.string(),
        }),
      ),
      async (c) => {
        const { location } = c.req.valid("json")
        await Skill.remove(location)
        return c.json(true)
      },
    )
    .post(
      "/agent/remove",
      describeRoute({
        summary: "Remove a custom agent",
        description: "Remove a custom (non-native) agent by deleting its markdown file from disk and refreshing state.",
        operationId: "saeeol.removeAgent",
        responses: {
          200: {
            description: "Agent removed",
            content: {
              "application/json": {
                schema: resolver(z.boolean()),
              },
            },
          },
          ...errors(400),
        },
      }),
      validator(
        "json",
        z.object({
          name: z.string(),
        }),
      ),
      async (c) => {
        const { name } = c.req.valid("json")
        await Agent.remove(name)
        return c.json(true)
      },
    ),
)
