import { NextRequest, NextResponse } from 'next/server'
import { generateSorobanSVG } from '@/lib/typst-soroban'

export async function POST(request: NextRequest) {
  try {
    const config = await request.json()

    // Debug: log the received config
    console.log('🔍 Preview config:', JSON.stringify(config, null, 2))

    // Ensure range is set with a default
    if (!config.range) {
      config.range = '0-9'
    }

    // For preview, limit to a few numbers and use SVG format for fast rendering
    const previewConfig = {
      ...config,
      range: getPreviewRange(config.range),
      format: 'svg', // Use SVG format for preview
      cardsPerPage: 6 // Standard card layout
    }

    console.log('🔍 Processed preview config:', JSON.stringify(previewConfig, null, 2))

    // Generate real SVG preview using typst.ts
    console.log('🚀 Generating soroban SVG preview via typst.ts')

    try {
      // Parse the numbers from the range for individual cards
      const numbers = parseNumbersFromRange(getPreviewRange(config.range))
      console.log('🔍 Generating individual SVGs for numbers:', numbers)

      // Generate individual SVGs for each number using typst.ts
      const samples = []
      for (const number of numbers) {
        try {
          const typstConfig = {
            number: number,
            beadShape: previewConfig.beadShape || 'diamond',
            colorScheme: previewConfig.colorScheme || 'place-value',
            hideInactiveBeads: previewConfig.hideInactiveBeads || false,
            scaleFactor: previewConfig.scaleFactor || 1.0,
            width: '200pt',
            height: '250pt'
          }
          console.log(`🔍 Generating typst.ts SVG for number ${number}`)
          const svg = await generateSorobanSVG(typstConfig)
          console.log(`✅ Generated typst.ts SVG for ${number}, length: ${svg.length}`)
          samples.push({
            number,
            front: svg,
            back: number.toString()
          })
        } catch (error) {
          console.error(`❌ Failed to generate SVG for number ${number}:`, error instanceof Error ? error.message : error)
          samples.push({
            number,
            front: `<svg width="200" height="300" viewBox="0 0 200 300" xmlns="http://www.w3.org/2000/svg">
              <rect x="10" y="10" width="180" height="280" fill="none" stroke="#ccc" stroke-width="2"/>
              <line x1="20" y1="150" x2="180" y2="150" stroke="#ccc" stroke-width="2"/>
              <text x="100" y="160" text-anchor="middle" font-size="24" fill="#666">SVG Error</text>
              <text x="100" y="180" text-anchor="middle" font-size="16" fill="#999">${number}</text>
            </svg>`,
            back: number.toString()
          })
        }
      }

      return NextResponse.json({
        count: numbers.length,
        samples,
        note: 'Real individual SVGs generated by typst.ts'
      })

    } catch (error) {
      console.error('⚠️ Typst.ts SVG generation failed, using fallback preview:', error instanceof Error ? error.message : error)
      return NextResponse.json(getMockPreviewData(config))
    }

  } catch (error) {
    console.error('❌ Preview generation failed:', error)

    // Always fall back to mock data for preview
    const config = await request.json().catch(() => ({ range: '0-9' }))
    return NextResponse.json(getMockPreviewData(config))
  }
}

// Helper function to parse numbers from range string
function parseNumbersFromRange(range: string): number[] {
  if (!range) return [0, 1, 2]

  if (range.includes('-')) {
    const [start] = range.split('-')
    const startNum = parseInt(start) || 0
    return [startNum, startNum + 1, startNum + 2]
  }

  if (range.includes(',')) {
    return range.split(',').slice(0, 3).map(n => parseInt(n.trim()) || 0)
  }

  const num = parseInt(range) || 0
  return [num, num + 1, num + 2]
}

// Helper function to limit range for preview
function getPreviewRange(range: string): string {
  if (!range) return '0,1,2'

  if (range.includes('-')) {
    const [start] = range.split('-')
    const startNum = parseInt(start) || 0
    return `${startNum},${startNum + 1},${startNum + 2}`
  }

  if (range.includes(',')) {
    const numbers = range.split(',').slice(0, 3)
    return numbers.join(',')
  }

  return range
}

// Mock preview data for development and fallback
function getMockPreviewData(config: any) {
  const range = config.range || '0-9'
  let numbers: number[]

  if (range.includes('-')) {
    const [start] = range.split('-')
    const startNum = parseInt(start) || 0
    numbers = [startNum, startNum + 1, startNum + 2]
  } else if (range.includes(',')) {
    numbers = range.split(',').slice(0, 3).map((n: string) => parseInt(n.trim()) || 0)
  } else {
    const num = parseInt(range) || 0
    numbers = [num, num + 1, num + 2]
  }

  return {
    count: numbers.length,
    samples: numbers.map(number => ({
      number,
      front: `<svg width="200" height="300" viewBox="0 0 200 300" xmlns="http://www.w3.org/2000/svg">
        <rect x="10" y="10" width="180" height="280" fill="none" stroke="#ccc" stroke-width="2"/>
        <line x1="20" y1="150" x2="180" y2="150" stroke="#ccc" stroke-width="2"/>
        <text x="100" y="160" text-anchor="middle" font-size="24" fill="#666">Preview Error</text>
        <text x="100" y="180" text-anchor="middle" font-size="16" fill="#999">${number}</text>
      </svg>`,
      back: number.toString()
    }))
  }
}

// Health check endpoint
export async function GET() {
  return NextResponse.json({
    status: 'healthy',
    endpoint: 'preview',
    message: 'Preview API is running'
  })
}