import { GoogleGenerativeAI } from "@google/generative-ai"
import { draw, type DrawCommand } from "./draw"
import { sendGrid } from "./vestaboard"

const buildSystemPrompt = async (): Promise<string> => {
  const promptMd = await Bun.file(`${import.meta.dir}/prompt.md`).text()
  const examplesJson = await Bun.file(`${import.meta.dir}/examples.json`).json()

  const examplesText = examplesJson.goldExamples
    .map((ex: { input: string; output: unknown }) => `Input: "${ex.input}"\nOutput: ${JSON.stringify(ex.output)}`)
    .join("\n\n")

  return `${promptMd}

## Examples

${examplesText}`
}

export const generateVestaboard = async (query: string): Promise<string> => {
  const apiKey = process.env.GEMINI_API_KEY
  if (!apiKey) {
    throw new Error("GEMINI_API_KEY not set in environment")
  }

  const genAI = new GoogleGenerativeAI(apiKey)
  const model = genAI.getGenerativeModel({
    model: "gemini-2.5-flash",
    generationConfig: {
      temperature: 0.7,
      responseMimeType: "application/json",
    },
  })

  const systemPrompt = await buildSystemPrompt()

  const result = await model.generateContent(`${systemPrompt}\n\n## User Request\n\n${query}`)
  const text = result.response.text()

  let commands: DrawCommand[]
  try {
    commands = JSON.parse(text)
  } catch {
    throw new Error(`Failed to parse Gemini response as JSON: ${text}`)
  }

  if (!Array.isArray(commands)) {
    throw new Error(`Expected array of commands, got: ${typeof commands}`)
  }

  const grid = draw(commands)
  await sendGrid(grid)

  return "The vestaboard design has been generated and sent successfully."
}
