/**
 * Medición de tamaños de CSV para los 3 sample BPMNs.
 * Este test calcula el tamaño en bytes del CSV generado para cada BPMN.
 */
import { describe, it } from 'vitest'
import { readFileSync } from 'fs'
import { resolve } from 'path'
import { v4 as uuidv4 } from 'uuid'
import { parseBpmnXml, extractActivityElements, extractGatewayElements } from '@/domain/bpmn-parser'
import { runSimulation } from '@/domain/simulation'
import { generateCsvContent } from '@/lib/export/csv-export'
import { bpmnTypeToGatewayType } from '@/domain/types'
import type { Activity, GatewayConfig, SimulationInput, Process, Simulation } from '@/domain/types'

function loadBpmn(name: string): string {
  return readFileSync(resolve(__dirname, '../../../public/sample-processes', name), 'utf-8')
}

function buildInput(xml: string, directCost: number): SimulationInput {
  const graph = parseBpmnXml(xml)
  const actEls = extractActivityElements(graph)
  const gwEls = extractGatewayElements(graph)
  const processId = 'measure-proc'

  const activities = new Map<string, Activity>(
    actEls.map((el) => [el.bpmnElementId, {
      id: uuidv4(), processId, bpmnElementId: el.bpmnElementId, name: el.name,
      type: el.type, directCostFixed: directCost, executionTimeMinutes: 30, assignedResources: [],
      automatable: false, automatedCostFixed: 0, automatedTimeMinutes: 0, automatedAssignedResources: [],
    }])
  )

  const gateways = new Map<string, GatewayConfig>(
    gwEls.map((el) => {
      const gwType = bpmnTypeToGatewayType(el.gatewayType as any)
      return [el.bpmnElementId, {
        id: uuidv4(), processId, bpmnElementId: el.bpmnElementId, gatewayType: gwType,
        branches: el.outgoing.map((flowId) => ({
          flowId, targetElementId: graph.flows.get(flowId)?.targetRef ?? '',
          probability: gwType === 'parallel' ? 1.0 : 1 / el.outgoing.length,
        })),
      }]
    })
  )

  return {
    processXml: xml, activities, gateways, resources: new Map(),
    globalSettings: { currency: 'USD', overheadPercentage: 0.2 },
  }
}

describe('Medición de tamaños de CSV — 3 sample BPMNs', () => {
  const BPMNS = [
    { file: 'simple-linear.bpmn', name: 'Proceso Lineal Simple', client: 'Demo' },
    { file: 'medium-with-gateways.bpmn', name: 'Aprobación de Crédito', client: 'Banco ABC' },
    { file: 'complex-with-loop.bpmn', name: 'Control de Calidad', client: 'Empresa XYZ' },
  ]

  for (const bpmn of BPMNS) {
    it(`${bpmn.file}: mide tamaño del CSV`, () => {
      const xml = loadBpmn(bpmn.file)
      const result = runSimulation(buildInput(xml, 1000))

      const process: Process = {
        id: 'p1', name: bpmn.name, clientName: bpmn.client,
        bpmnXml: xml, currency: 'USD', overheadPercentage: 0.2,
        annualFrequency: 1000, analysisHorizonYears: 3, automationInvestment: 0,
        createdAt: 0, updatedAt: 0,
        groupId: null, tags: [],
      }

      const simulation: Simulation = {
        id: 's1', processId: 'p1',
        executedAt: new Date('2026-05-13T12:00:00Z').getTime(),
        result,
      }

      const csv = generateCsvContent({ process, simulation, resources: [] })
      const bytes = new TextEncoder().encode(csv).length

      console.log(`\n📊 ${bpmn.file}`)
      console.log(`   Actividades: ${result.perActivity.length}`)
      console.log(`   CSV size: ${bytes} bytes (${(bytes / 1024).toFixed(1)} KB)`)
      console.log(`   CSV líneas de datos: ${result.perActivity.length} + 1 header + 7 meta`)
      console.log(`   Costo total: $${result.totalCost.toFixed(2)}`)

      // El CSV no debe ser vacío
      expect(bytes).toBeGreaterThan(100)
    })
  }
})
