import { compileTixyExpression, renderTixyToCanvas, EXAMPLE_EXPRESSIONS } from '../tixy-generator'
import type { GeneratedImage } from '../stores'

const expressions = Object.keys(EXAMPLE_EXPRESSIONS)

const colorPalettes = [
  { bg: '#000000', fg: '#ffffff' },
  { bg: '#ffffff', fg: '#000000' },
  { bg: '#000000', fg: '#cccccc' },
  { bg: '#000000', fg: '#888888' },
  { bg: '#1a1a1a', fg: '#ffffff' },
  { bg: '#333333', fg: '#ffffff' },
  { bg: '#000000', fg: '#666666' },
  { bg: '#222222', fg: '#dddddd' }
]

export function generateTixyImages(count: number, size: number): GeneratedImage[] {
  const images: GeneratedImage[] = []

  for (let i = 0; i < count; i++) {
    const expression = expressions[Math.floor(Math.random() * expressions.length)]

    let time: number
    if (Math.random() < 0.3) {
      time = Math.random() * 2
    } else if (Math.random() < 0.6) {
      time = Math.random() * 20
    } else {
      time = Math.random() * 100
    }

    const palette = colorPalettes[Math.floor(Math.random() * colorPalettes.length)]

    try {
      const compiled = compileTixyExpression(expression)

      const result = renderTixyToCanvas(compiled, {
        width: size,
        height: size,
        time,
        backgroundColor: palette.bg,
        foregroundColor: palette.fg
      })

      const image = {
        id: `tixy-${Date.now()}-${i}`,
        canvas: result.canvas,
        imageData: result.imageData,
        generator: 'tixy',
        params: { expression, time, colors: palette }
      }

      images.push(image)
    } catch (error) {
      console.error(`Failed to generate Tixy image ${i + 1}:`, error)
    }
  }

  return images
}