/**
 * fal.ai Client for image generation
 *
 * Uses fal.ai's API to generate images via AI models.
 */

export interface FalImageResult {
  url: string;
  width: number;
  height: number;
  content_type: string;
}

export interface FalGenerateResponse {
  images: FalImageResult[];
}

export class FalClient {
  private apiKey: string;
  private baseUrl = "https://fal.run";

  constructor(apiKey?: string) {
    this.apiKey = apiKey || process.env.FAL_API_KEY || "";
    if (!this.apiKey) {
      throw new Error("FAL_API_KEY is required");
    }
  }

  /**
   * Generate images using fal.ai's flux-schnell model
   * Generates 2 images by default
   */
  async generateImages(
    prompt: string,
    options?: {
      numImages?: number;
      imageSize?:
        | "square_hd"
        | "square"
        | "portrait_4_3"
        | "portrait_16_9"
        | "landscape_4_3"
        | "landscape_16_9";
    }
  ): Promise<FalGenerateResponse> {
    const numImages = options?.numImages ?? 2;
    const imageSize = options?.imageSize ?? "square_hd";

    try {
      const response = await fetch(`${this.baseUrl}/fal-ai/flux/schnell`, {
        method: "POST",
        headers: {
          Authorization: `Key ${this.apiKey}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          prompt,
          image_size: imageSize,
          num_inference_steps: 4, // schnell is optimized for 4 steps
          num_images: numImages,
          enable_safety_checker: true,
        }),
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(
          `fal.ai API error: ${response.status} ${response.statusText} - ${errorText}`
        );
      }

      const data = await response.json();
      return data as FalGenerateResponse;
    } catch (error) {
      console.error("fal.ai generation failed:", error);
      throw error;
    }
  }

  /**
   * Download image from URL and return as Buffer
   */
  async downloadImage(url: string): Promise<ArrayBuffer> {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Failed to download image: ${response.statusText}`);
    }
    return await response.arrayBuffer();
  }
}

export function createFalClient(apiKey?: string): FalClient {
  return new FalClient(apiKey);
}
