/**
 * Etapa 10 Sprint 1.5 — Generación de PDFs baseline final del sprint.
 * Genera los 3 PDFs de referencia en tests/e2e/__output__/sprint-1-5-final/
 * NO es un test de regresión — es el artefacto baseline para Sprint 2.
 */
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__/sprint-1-5-final')

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
}

async function setupFullScenario(page: import('@playwright/test').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)
}

async function downloadTab(page: import('@playwright/test').Page, tab: 'actual' | 'automatizado' | 'roi', outPath: string) {
  if (tab === 'actual') {
    await page.getByRole('tab', { name: 'Actual' }).click()
    await page.waitForTimeout(400)
  } else if (tab === 'automatizado') {
    await page.getByRole('tab', { name: 'Automatizado' }).click()
    await page.waitForTimeout(400)
  } else {
    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 [download] = await Promise.all([
    page.waitForEvent('download', { timeout: 30_000 }),
    page.getByRole('button', { name: 'Exportar PDF' }).click(),
  ])
  await download.saveAs(outPath)
}

test('sprint-1-5-final: generar y validar 3 PDFs baseline', async ({ page }) => {
  await setupFullScenario(page)

  // PDF Actual
  const actualPath = resolve(OUT_DIR, 'final-actual.pdf')
  await downloadTab(page, 'actual', actualPath)
  const actualBuf = readFileSync(actualPath)
  const actualKB = (actualBuf.length / 1024).toFixed(1)
  const { numpages: actualPages } = await parsePdf(actualBuf)
  const actualOrientations = await getOrientations(actualBuf)
  console.log(`final-actual.pdf: ${actualPages} págs, ${actualKB} KB, ${actualOrientations.join(',')}`)
  expect(actualPages).toBe(4)
  expect(actualOrientations).toEqual(['portrait', 'landscape', 'portrait', 'portrait'])

  // PDF Automatizado
  const autoPath = resolve(OUT_DIR, 'final-automatizado.pdf')
  await downloadTab(page, 'automatizado', autoPath)
  const autoBuf = readFileSync(autoPath)
  const autoKB = (autoBuf.length / 1024).toFixed(1)
  const { numpages: autoPages } = await parsePdf(autoBuf)
  const autoOrientations = await getOrientations(autoBuf)
  console.log(`final-automatizado.pdf: ${autoPages} págs, ${autoKB} KB, ${autoOrientations.join(',')}`)
  expect(autoPages).toBe(4)
  expect(autoOrientations).toEqual(['portrait', 'landscape', 'portrait', 'portrait'])

  // PDF ROI
  const roiPath = resolve(OUT_DIR, 'final-roi.pdf')
  await downloadTab(page, 'roi', roiPath)
  const roiBuf = readFileSync(roiPath)
  const roiKB = (roiBuf.length / 1024).toFixed(1)
  const { numpages: roiPages, text: roiText } = await parsePdf(roiBuf)
  const roiOrientations = await getOrientations(roiBuf)
  console.log(`final-roi.pdf: ${roiPages} págs, ${roiKB} KB, ${roiOrientations.join(',')}`)
  expect(roiPages).toBe(5)
  expect(roiOrientations).toEqual(['portrait', 'portrait', 'portrait', 'portrait', 'portrait'])
  expect(roiText).toMatch(/AHORRO PROYECTADO A/)
  expect(roiText).toMatch(/TRAYECTORIA DEL AHORRO ACUMULADO/)
  expect(roiText).toMatch(/InQ ROI/)
  expect(roiText).toMatch(/Powered by InQuality/)
})
