/**
 * Generuje CSV do ręcznej weryfikacji: producent, kraj (ISO alpha-2), widoczność wg segmentów ogłoszeń.
 * Uruchom: npm run export-manufacturers-csv
 */
import { mkdirSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'

import { BOAT_MANUFACTURER_RECORDS } from '../data/boat-manufacturers'

const __dirname = dirname(fileURLToPath(import.meta.url))

const SEGMENT_IDS = ['sail', 'power', 'inflatable', 'small', 'engine', 'trailer'] as const

function csvCell(raw: string): string {
  if (/[,"\r\n]/.test(raw)) return `"${raw.replace(/"/g, '""')}"`
  return raw
}

function rowToLine(cells: string[]): string {
  return cells.map(csvCell).join(',')
}

const header = [
  'producent',
  'kraj_iso3166_alpha2',
  /** puste = „brak przypisanego kraju” w aplikacji (do uzupełnienia) */
  'brak_kraju_w_danych',
  /** Kategorie z formularza/wyszukiwarki: sail=żaglowe, power=motorowe, … */
  ...SEGMENT_IDS.map((id) => `kategoria_${id}`),
]

const lines: string[] = [rowToLine(header)]

for (const m of BOAT_MANUFACTURER_RECORDS) {
  const country = m.countryCode ?? ''
  const flags = SEGMENT_IDS.map((id) => (m.segments.includes(id) ? 'tak' : 'nie'))
  lines.push(rowToLine([m.name, country, country === '' ? 'tak' : 'nie', ...flags]))
}

const outPath = join(__dirname, '..', 'data', 'manufacturers-verification.csv')
mkdirSync(dirname(outPath), { recursive: true })
writeFileSync(outPath, '\uFEFF' + lines.join('\n') + '\n', 'utf8')

console.log(`Wrote ${outPath} (${BOAT_MANUFACTURER_RECORDS.length} wierszy)`)
