import { promisify } from 'node:util'
import child_process from 'node:child_process'
import { existsSync, mkdirSync } from 'node:fs'
import { writeFile } from 'node:fs/promises'
import { detectPdfPage, withMediaOption } from '../../utils/pdfPageMedia'

// Map shipping printer to Tisch number for A4 printer naming
const SHIPPING_PRINTER_TO_TISCH: Record<string, string> = {
  'labelprinter-1': '1', // Tisch 1
  'labelprinter-4': '2', // Tisch 2
  'labelprinter-5': '3'  // Tisch 3
}

export default defineEventHandler(async (event) => {
  let data: any = {}
  const body = await readBody(event)
  const exec = promisify(child_process.exec)
  const pathName = body.pathName
  const filePath = `/root/storage/${pathName}`
  const fileName = body.fileName
  const fileContent = Buffer.from(body.fileContent, 'base64')
  const shippingPrinter = body.shippingPrinter || 'labelprinter-1'

  // Prefer the A4 printer configured on the commissioning table
  // (CUST_CommissionTable.a4_printer, passed by the client). Fall back to the
  // legacy printer→Tisch map for callers that don't send it.
  const tischNumber = SHIPPING_PRINTER_TO_TISCH[shippingPrinter] || '1'
  const a4Printer = body.a4Printer || `commission-a4-${tischNumber}`

  try {
    if (!existsSync(filePath)) {
      mkdirSync(filePath, { recursive: true })
    }
    const fullFilePath = `${filePath}/${fileName}`
    await writeFile(fullFilePath, fileContent)

    // Page size decides the queue: labels → shipping label printer (fit-to-page);
    // A5 / A4 paper → the commissioning table's A4 printer with an explicit media
    // size, so an A5 Lieferschein pulls A5 from the tray instead of landing on the
    // Zebra. See server/utils/pdfPageMedia.ts.
    const page = await detectPdfPage(fullFilePath)
    const pdfWidth = page.width
    const pdfHeight = page.height
    const isSmallLabel = page.kind === 'label'
    console.log(`[Smart Print] PDF dimensions: ${pdfWidth} x ${pdfHeight} pts (${page.kind}${page.detected ? '' : ', assumed'})`)

    const printerToUse = isSmallLabel ? shippingPrinter : a4Printer
    const printOptions = isSmallLabel ? '-o fit-to-page' : withMediaOption('-o sides=one-sided', page)

    console.log(`[Smart Print] Printing to: ${printerToUse} with options: ${printOptions}`)

    const { stdout, stderr } = await exec(`lp -d ${printerToUse} ${printOptions} "${fullFilePath}"`)

    data = {
      ...body,
      message: !stderr ? 'success' : 'failed',
      stdout: stdout,
      stderr: stderr,
      pdfAnalysis: {
        width: pdfWidth,
        height: pdfHeight,
        isSmallLabel: isSmallLabel,
        kind: page.kind,
        media: page.mediaOption || null,
        printerUsed: printerToUse
      }
    }
  } catch (err: any) {
    console.error('[Smart Print] Error:', err)
    data = {
      message: 'failed',
      error: err.message || err
    }
  }

  return data
})
