/**
 * Etapa 11 Parte A — Genera el PDF ROI con los 4 refinamientos del polish final.
 * Guarda en tests/e2e/__output__/etapa-11-roi.pdf para validación visual del director.
 */
import { test, expect } from '@playwright/test'
import { resolve } from 'path'
import { mkdirSync, readFileSync } from 'fs'
import { fileURLToPath } from 'url'
import { PDFParse } from 'pdf-parse'
import { getDocument } from 'pdfjs-dist/legacy/build/pdf.mjs'

const __dirname = fileURLToPath(new URL('.', import.meta.url))
const BPMN_DIR = resolve(__dirname, '../../public/sample-processes')
const OUT_DIR = resolve(__dirname, './__output__')

test.beforeAll(() => { mkdirSync(OUT_DIR, { recursive: true }) })

async function parsePdf(buffer: Buffer) {
  const parser = new PDFParse({ data: buffer })
  const result = await parser.getText()
  await parser.destroy()
  return { numpages: result.total, text: result.text }
}

async function getOrientations(buffer: Buffer): Promise<string[]> {
  const uint8 = new Uint8Array(buffer)
  const pdf = await getDocument({ data: uint8 }).promise
  const out: string[] = []
  for (let i = 1; i <= pdf.numPages; i++) {
    const page = await pdf.getPage(i)
    const vp = page.getViewport({ scale: 1 })
    out.push(vp.width > vp.height ? 'landscape' : 'portrait')
  }
  return out
}

test('etapa-11-roi.pdf — polish final página 1 ROI', async ({ page }) => {
  await page.goto('/')
  await page.locator('#bpmn-file-input').setInputFiles(resolve(BPMN_DIR, 'medium-with-gateways.bpmn'))
  await page.waitForURL(/\/workspace\//, { timeout: 15_000 })
  await page.waitForSelector('button:has-text("Simular")', { timeout: 10_000 })
  await page.waitForTimeout(800)

  for (const [id, cost, auto] of [
    ['task_recv', 200, 20], ['task_score', 200, 20], ['task_analisis', 200, 20]
  ] as [string, number, number][]) {
    await page.locator(`[data-element-id="${id}"]`).first().click()
    await page.waitForTimeout(400)
    const toggle = page.getByRole('switch', { name: /automatizable/i })
    if (await toggle.getAttribute('aria-checked') === 'false') await toggle.click()
    await page.waitForTimeout(200)
    await page.getByLabel(/Costo directo fijo/i).fill(String(cost))
    await page.getByLabel(/Costo automatizado/i).fill(String(auto))
    await page.getByLabel(/Tiempo automatizado/i).fill('10')
    await page.getByRole('button', { name: /Guardar/i }).click()
    await page.waitForTimeout(400)
  }

  await page.getByRole('tab', { name: /Global/i }).click()
  await page.waitForTimeout(300)
  await page.getByLabel(/Frecuencia anual/i).fill('5000')
  await page.getByLabel(/Inversión en automatización/i).fill('80000')
  await page.getByRole('button', { name: /Guardar/i }).click()
  await page.waitForTimeout(400)

  await page.getByRole('button', { name: 'Simular' }).click()
  await page.waitForURL(/\/report\//, { timeout: 20_000 })
  await page.waitForSelector('button:has-text("Exportar PDF")', { timeout: 15_000 })
  await page.waitForSelector('.bpmn-container .djs-group', { timeout: 30_000 })
  await page.waitForTimeout(800)

  await page.getByRole('tab', { name: /Comparación/i }).click()
  await page.waitForSelector('[data-testid="roi-kpi-card"]', { timeout: 10_000 })
  await page.waitForTimeout(500)

  const outPath = resolve(OUT_DIR, 'etapa-11-roi.pdf')
  const [download] = await Promise.all([
    page.waitForEvent('download', { timeout: 30_000 }),
    page.getByRole('button', { name: 'Exportar PDF' }).click(),
  ])
  await download.saveAs(outPath)

  const buffer = readFileSync(outPath)
  const sizeKB = (buffer.length / 1024).toFixed(1)
  const { numpages, text } = await parsePdf(buffer)
  const orientations = await getOrientations(buffer)

  console.log(`etapa-11-roi.pdf: ${numpages} págs, ${sizeKB} KB`)
  console.log(`Texto p.1 (500 chars): ${text.slice(0, 500).replace(/\n/g, ' ')}`)
  console.log(`Orientaciones: ${orientations.join(', ')}`)

  expect(numpages).toBe(5)
  expect(orientations).toEqual(['portrait', 'portrait', 'portrait', 'portrait', 'portrait'])
  expect(text).toMatch(/AHORRO PROYECTADO A/)
  expect(text).toMatch(/TOP 3 ACTIVIDADES POR AHORRO/)
  expect(text).toMatch(/InQ ROI/)
  expect(text).toMatch(/Powered by InQuality/)
})
