import { NamedError } from "@saeeol/core/util/error"
import { Glob } from "@saeeol/core/util/glob"
import { Instance } from "../../project/instance"
import { InstanceStore } from "../../project/instance-store"
import { makeRuntime } from "@/effect/run-service"
import z from "zod"
import path from "path"

export const RemoveError = NamedError.create(
  "AgentRemoveError",
  z.object({
    name: z.string(),
    message: z.string(),
  }),
)

export async function remove(name: string) {
  const { Agent } = await import("../../agent/agent")
  const agents = makeRuntime(Agent.Service, Agent.defaultLayer)
  const agent = await agents.runPromise((svc) => svc.get(name))
  if (!agent) throw new RemoveError({ name, message: "agent not found" })
  if (agent.native) throw new RemoveError({ name, message: "cannot remove native agent" })
  if (agent.options?.source === "organization")
    throw new RemoveError({ name, message: "cannot remove organization agent — manage it from the cloud dashboard" })

  const { unlink, writeFile } = await import("fs/promises")
  let found = false

  const { Config } = await import("../../config/config")
  const dirs = await Config.directories()
  const patterns = ["{agent,agents}/**/" + name + ".md", "{mode,modes}/" + name + ".md"]
  for (const dir of dirs) {
    for (const pattern of patterns) {
      const matches = await Glob.scan(pattern, { cwd: dir, absolute: true, dot: true })
      for (const file of matches) {
        if (await Bun.file(file).exists()) {
          await unlink(file)
          found = true
        }
      }
    }
  }

  const { ModesMigrator } = await import("@/saeeol/modes-migrator")
  const { SaeeolPaths } = await import("@/saeeol/paths")
  const os = await import("os")
  const matter = (await import("gray-matter")).default
  const home = os.default.homedir()
  const modesFiles = [
    path.join(SaeeolPaths.vscodeGlobalStorage(), "settings", "custom_modes.yaml"),
    path.join(home, ".saeeol", "cli", "global", "settings", "custom_modes.yaml"),
    path.join(home, ".saeeolmodes"),
    path.join(Instance.directory, ".saeeolmodes"),
  ]

  for (const file of modesFiles) {
    const modes = await ModesMigrator.readModesFile(file)
    if (!modes.length) continue

    const filtered = modes.filter((m: { slug: string }) => m.slug !== name)
    if (filtered.length === modes.length) continue

    const yaml = matter
      .stringify("", { customModes: filtered })
      .replace(/^---\n/, "")
      .replace(/\n---\n?$/, "")
    await writeFile(file, yaml)
    found = true
  }

  if (!found) throw new RemoveError({ name, message: "no agent file found on disk" })

  await InstanceStore.disposeInstance(Instance.current)
}
