import type { ImportRow } from '@/lib/domain/pilot-network'

/**
 * CSV for the full pilot dataset (§27): header row with name, company,
 * phone, email, state, capabilities (capabilities separated by `;` or `|`
 * inside the cell). Quoted cells with commas are supported. Pure — used by
 * the admin import route and testable without I/O.
 */
export function parseLeadsCsv(text: string): { rows: ImportRow[]; errors: string[] } {
  const lines = splitCsvLines(text.replace(/^﻿/, ''))
  const errors: string[] = []
  if (lines.length < 2) return { rows: [], errors: ['The file needs a header row and at least one lead.'] }
  const header = parseCsvLine(lines[0]).map((h) => h.trim().toLowerCase().replace(/[^a-z0-9]+/g, '_'))
  const col = (names: string[]) => header.findIndex((h) => names.includes(h))
  const iName = col(['name', 'contact_name', 'contact'])
  const iCompany = col(['company', 'company_name'])
  const iPhone = col(['phone', 'phone_number'])
  const iEmail = col(['email', 'email_address'])
  const iState = col(['state', 'primary_state'])
  const iCaps = col(['capabilities', 'capability', 'positions', 'escort_positions'])
  if (iName < 0 || iEmail < 0 || iState < 0) return { rows: [], errors: ['Missing required columns: name, email, state.'] }
  const rows: ImportRow[] = []
  for (let i = 1; i < lines.length; i++) {
    if (!lines[i].trim()) continue
    const cells = parseCsvLine(lines[i])
    const get = (idx: number) => (idx >= 0 ? (cells[idx] ?? '').trim() : '')
    const caps = get(iCaps)
    rows.push({
      name: get(iName),
      company: get(iCompany) || null,
      phone: get(iPhone) || null,
      email: get(iEmail),
      state: get(iState).toUpperCase(),
      capabilities: caps ? caps.split(/[;|]/).map((c) => c.trim()).filter(Boolean) : [],
    })
  }
  return { rows, errors }
}

function splitCsvLines(text: string): string[] {
  const out: string[] = []
  let cur = ''
  let quoted = false
  for (let i = 0; i < text.length; i++) {
    const ch = text[i]
    if (ch === '"') quoted = !quoted
    if ((ch === '\n' || ch === '\r') && !quoted) {
      if (cur.length) out.push(cur)
      cur = ''
      if (ch === '\r' && text[i + 1] === '\n') i++
      continue
    }
    cur += ch
  }
  if (cur.length) out.push(cur)
  return out
}

function parseCsvLine(line: string): string[] {
  const cells: string[] = []
  let cur = ''
  let quoted = false
  for (let i = 0; i < line.length; i++) {
    const ch = line[i]
    if (ch === '"') {
      if (quoted && line[i + 1] === '"') {
        cur += '"'
        i++
      } else quoted = !quoted
      continue
    }
    if (ch === ',' && !quoted) {
      cells.push(cur)
      cur = ''
      continue
    }
    cur += ch
  }
  cells.push(cur)
  return cells
}
