import { SessionID, MessageID } from "@/session/schema"
import { Identifier } from "@/id/id"
import { LLM } from "@/session/llm"
import { MessageV2 } from "@/session/message-v2"
import * as Log from "@saeeol/core/util/log"
import { PlanFollowupRuntime } from "./plan-followup-runtime"

export function formatTodos(todos: { status: string; content: string }[]): string {
  if (!todos.length) return ""
  const icons: Record<string, string> = {
    completed: "[x]",
    in_progress: "[~]",
    cancelled: "[-]",
  }
  return todos.map((t) => `- ${icons[t.status] ?? "[ ]"} ${t.content}`).join("\n")
}

export async function generateHandover(input: {
  messages: MessageV2.WithParts[]
  model: MessageV2.User["model"]
  abort?: AbortSignal
}): Promise<string> {
  const log = Log.create({ service: "plan.followup" })
  try {
    const entry = await PlanFollowupRuntime.agent("compaction")
    const model = entry?.model
      ? await PlanFollowupRuntime.model(entry.model.providerID, entry.model.modelID)
      : await PlanFollowupRuntime.model(input.model.providerID, input.model.modelID)

    const sessionID = SessionID.make(Identifier.ascending("session"))
    const userMsg: MessageV2.User = {
      id: MessageID.ascending(),
      sessionID,
      role: "user",
      time: { created: Date.now() },
      agent: "plan",
      model: input.model,
    }

    const { HANDOVER_PROMPT } = await import("./plan-followup-runtime")
    const stream = await LLM.stream({
      agent: entry ?? { name: "compaction", mode: "subagent", permission: [], options: {} },
      user: userMsg,
      tools: {},
      model,
      small: true,
      messages: [
        ...(await MessageV2.toModelMessages(input.messages, model)),
        { role: "user" as const, content: HANDOVER_PROMPT },
      ],
      abort: input.abort ? AbortSignal.any([input.abort, AbortSignal.timeout(60_000)]) : AbortSignal.timeout(60_000),
      sessionID,
      system: [],
      retries: 1,
    })

    const result = await stream.text
    return result.trim()
  } catch (error) {
    if (input.abort?.aborted) return ""
    log.error("handover generation failed", { error })
    return ""
  }
}
