export * as ConfigCommand from "./command"

import * as Log from "@saeeol/core/util/log"
import { Schema } from "effect"
import { NamedError } from "@saeeol/core/util/error"
import { Glob } from "@saeeol/core/util/glob"
import { Bus } from "@/bus"
import { zod } from "@/util/effect-zod"
import { withStatics } from "@/util/schema"
import { configEntryNameFromPath } from "./entry-name"
import * as ConfigMarkdown from "./markdown"
import { ConfigModelID } from "./model-id"
import { SaeeolConfig } from "@/saeeol/config/config"
import type { Warning } from "./config"

const log = Log.create({ service: "config" })

export const Info = Schema.Struct({
  template: Schema.String,
  description: Schema.optional(Schema.String),
  agent: Schema.optional(Schema.String),
  model: Schema.optional(ConfigModelID),
  subtask: Schema.optional(Schema.Boolean),
}).pipe(withStatics((s) => ({ zod: zod(s) })))

export type Info = Schema.Schema.Type<typeof Info>
export async function load(dir: string, warnings?: Warning[]) {
  const result: Record<string, Info> = {}
  for (const item of await Glob.scan("{command,commands}/**/*.md", {
    cwd: dir,
    absolute: true,
    dot: true,
    symlink: true,
  })) {
    const md = await ConfigMarkdown.parse(item).catch(async (err) => {
      const message = ConfigMarkdown.FrontmatterError.isInstance(err)
        ? err.data.message
        : `Failed to parse command ${item}`
      if (warnings) warnings.push({ path: item, message })
      try {
        const { Session } = await import("@/session/session")
        Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() })
      } catch (e) {
        log.warn("could not publish session error", { message, err: e })
      }
      log.error("failed to load command", { command: item, err })
      return undefined
    })
    if (!md) continue
    const patterns = [
      "/.saeeol/command/",
      "/.saeeol/commands/",
      "/.saeeol/command/",
      "/.saeeol/commands/",
      "/.saeeol/command/",
      "/.saeeol/commands/",
      "/command/",
      "/commands/",
    ]
    const name = configEntryNameFromPath(item, patterns)

    const config = {
      name,
      ...md.data,
      template: md.content.trim(),
    }
    const parsed = Info.zod.safeParse(config)
    if (parsed.success) {
      result[config.name] = parsed.data
      continue
    }
    await SaeeolConfig.handleInvalid("command", item, parsed.error.issues, parsed.error, warnings)
  }
  return result
}
