import { GoogleGenAI, Type } from "@google/genai"
import { z, ZodObject } from "zod"
import { Agent, run, user, type AgentInputItem } from "@openai/agents"

export const getGeminiResponse = async <T = StructuredResponse>(
  imageArrayBuffer: ArrayBuffer,
  prompt: string
): Promise<T | undefined> => {
  try {
    const ai = new GoogleGenAI({})
    const base64ImageData = Buffer.from(imageArrayBuffer).toString("base64")

    const contents = [
      {
        inlineData: {
          mimeType: "image/jpeg",
          data: base64ImageData,
        },
      },
      { text: prompt },
    ]

    const response = await ai.models.generateContent({
      model: "gemini-2.5-flash",
      // model: "gemini-2.5-flash-lite-preview-06-17",
      contents: contents,
      config: {
        thinkingConfig: {
          thinkingBudget: 0,
        },
        responseMimeType: "application/json",
        responseSchema: whiteboardSchema,
      },
    })

    const responseText = response.text
    if (!responseText) {
      throw new Error("No response received from Gemini")
    }

    try {
      return JSON.parse(responseText)
    } catch (parseError) {
      console.error("Failed to parse JSON response:", responseText)
      console.error("Parse error:", parseError)
      return undefined
    }
  } catch (error) {
    console.error("Error generating structured AI response:", error)
    return undefined
  }
}

// Zod schema for structured response
const StructuredResponseSchema = z.object({
  elements: z.array(
    z.object({
      ymin: z.number().describe("Normalized ymin coordinate (0-1000)"),
      xmin: z.number().describe("Normalized xmin coordinate (0-1000)"),
      ymax: z.number().describe("Normalized ymax coordinate (0-1000)"),
      xmax: z.number().describe("Normalized xmax coordinate (0-1000)"),
      label: z.string(),
    })
  ),
})

export const getOpenAIResponse = async <T = StructuredResponse>(
  imageArrayBuffer: ArrayBuffer,
  prompt: string
): Promise<T | undefined> => {
  try {
    const base64ImageData = Buffer.from(imageArrayBuffer).toString("base64")

    // Create an agent without outputType for now
    const agent = new Agent({
      name: "Whiteboard Analyzer",
      outputType: StructuredResponseSchema,
      model: "gpt-4o",
      instructions: prompt,
    })

    // Create input with image and prompt
    const input: AgentInputItem[] = [
      user([
        {
          type: "input_image",
          image: `data:image/jpeg;base64,${base64ImageData}`,
        },
      ]),
    ]

    const result = await run(agent, input)

    if (!result.finalOutput) {
      throw new Error("No response received from OpenAI Agent")
    }

    return result.finalOutput as T
  } catch (error) {
    console.error("Error generating structured AI response:", error)
    return
  }
}

export type StructuredResponse = z.infer<typeof StructuredResponseSchema>

const whiteboardSchema = {
  type: Type.OBJECT,
  properties: {
    elements: {
      type: Type.ARRAY,
      items: {
        type: Type.OBJECT,
        properties: {
          ymin: {
            type: Type.NUMBER,
            description: "Normalized ymin coordinate (0-1000)",
          },
          xmin: {
            type: Type.NUMBER,
            description: "Normalized xmin coordinate (0-1000)",
          },
          ymax: {
            type: Type.NUMBER,
            description: "Normalized ymax coordinate (0-1000)",
          },
          xmax: {
            type: Type.NUMBER,
            description: "Normalized xmax coordinate (0-1000)",
          },
          label: {
            type: Type.STRING,
          },
        },
        required: ["ymin", "xmin", "ymax", "xmax", "label"],
      },
    },
  },
  required: ["elements"],
}
