import type { TixyFunction, TixyExpression } from './types'

const MATH_METHODS = [
  'abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor',
  'log', 'max', 'min', 'pow', 'random', 'round', 'sin', 'sqrt', 'tan'
]

export function compileTixyExpression(code: string): TixyExpression {
  let processedCode = code.trim()

  for (const method of MATH_METHODS) {
    const regex = new RegExp(`\\b${method}\\(`, 'g')
    processedCode = processedCode.replace(regex, `Math.${method}(`)
  }

  try {
    const compiled = new Function('t', 'i', 'x', 'y', `return (${processedCode})`) as TixyFunction

    compiled(0, 0, 0, 0)

    return {
      code: processedCode,
      compiled
    }
  } catch (error) {
    throw new Error(`Failed to compile Tixy expression: ${error}`)
  }
}

export function evaluateTixyExpression(
  expression: TixyExpression,
  t: number,
  i: number,
  x: number,
  y: number
): number {
  try {
    const result = expression.compiled(t, i, x, y)
    return typeof result === 'number' && !isNaN(result) ? result : 0
  } catch {
    return 0
  }
}

export const EXAMPLE_EXPRESSIONS = {
  'sin(t)': 'Simple sine wave',
  'sin(t)*x': 'Sine wave with x scaling',
  'sin(t+x/8)*y': 'Traveling wave',
  '(x+t)*(y+t)': 'Expanding diagonal pattern',
  'sin(x*y+t)': 'XY interference pattern',
  'random()-0.5': 'Random noise',
  'sin(t)*cos(x*y/99)': 'Complex interference',
  '(x-8)*(y-8)/64': 'Centered gradient',
  'sin((x-8)**2+(y-8)**2+t)/2': 'Ripple from center',
  'x%2*y%2': 'Checkerboard pattern',
  'sin(t*2)*cos(x)*sin(y)': ' 3D wave interference',
  'abs(x-8)+abs(y-8)-t*4': 'Diamond expansion',
  'sin(x/4)*sin(y/4)*sin(t)': 'Grid waves',
  '(x*y)%16': 'Multiplication table',
  'sin(t+x*y/16)': 'Diagonal waves',
  'cos(t)*sin(x+y)': 'Corner waves',
  'min(x,y)-t*2': 'Corner fill',
  'max(x,y)+sin(t)': 'L-shape waves',
  'sin(t+x)*cos(t+y)': 'Phase shift grid',
  '(x+y+t*4)%8': 'Diagonal stripes',
  'sin(x*x+y*y+t)': 'Radial sine',
  'x*y/(i+1)': 'Index modulation',
  'tan(t)*sin(x*y/32)': 'Tangent interference',
  'floor(x/4)*floor(y/4)': 'Block pattern',
  'sin(t*3)*exp(-((x-8)**2+(y-8)**2)/32)': 'Gaussian pulse',
  'cos(x+t)*cos(y+t)': 'Corner cosines',
  '(x^y)%4': 'XOR pattern',
  'sin(sqrt(x*x+y*y)+t)': 'Circular waves',
  'abs(sin(t*x)*cos(t*y))': 'Absolute waves',
  '(x*t+y*t)%16': 'Time multiplication',
  'sin(t)*pow(x/16,2)': 'Parabolic wave',
  'cos(t+x/2)*sin(t+y/2)': 'Phase diagonal',
  'min(max(x-t,0),max(y-t,0))': 'Corner sweep',
  'sin(t+i/4)': 'Index time wave',
  'random()*sin(t+x+y)': 'Random wave',
  'floor(sin(t+x)*4)*floor(cos(t+y)*4)': 'Quantized waves',
  'abs(x-y)+sin(t*2)': 'Anti-diagonal waves',
  'pow(sin(t),2)*x*y/64': 'Squared sine',
  'sin(t*x/8)*cos(t*y/8)': 'Scaled time waves',
  'x*sin(t)+y*cos(t)': 'Rotating gradient'
}