import mammoth from 'mammoth'

export type ExperienceItem = {
  date: string
  role: string
  org: string
  details: string[]
}

const yearRe = /(19\d{2}|20\d{2})/g

function cleanLines(text: string) {
  return text
    .split(/\r?\n/)
    .map((l) => l.trim())
    .filter(Boolean)
}

function pickYearSpan(line: string) {
  const years = line.match(yearRe)
  if (!years?.length) return null
  // prefer "YYYY – YYYY" patterns
  const span = line.match(/(19\d{2}|20\d{2})\s*[-–]\s*(19\d{2}|20\d{2})/)
  if (span) return span[0].replace(/\s+/g, ' ').trim()
  if (years.length >= 1) return years[0]
  return null
}

function looksLikeRoleOrg(line: string) {
  const lc = line.toLowerCase()
  return (
    /(counsel|therap|clin|supervis|director|coordinator|intern|case|assistant)/i.test(line) &&
    lc.length >= 6
  )
}

// Best-effort: extract year-span + nearby role/org-ish lines.
export async function parseResumeDocx(url: string): Promise<ExperienceItem[]> {
  const res = await fetch(url)
  if (!res.ok) throw new Error(`Failed to fetch resume: ${res.status}`)
  const buf = await res.arrayBuffer()

  const result = await mammoth.extractRawText({
    // mammoth expects ArrayBuffer/Buffer
    arrayBuffer: buf as any,
  } as any)

  const lines = cleanLines(String(result.value ?? ''))

  // Find candidate lines with years.
  const candidates = lines
    .map((line, idx) => ({ line, idx, yearSpan: pickYearSpan(line) }))
    .filter((x) => x.yearSpan)

  if (!candidates.length) {
    // fallback: single bucket
    return [
      {
        date: 'Experience',
        role: 'Clinical Experience',
        org: '',
        details: lines.slice(0, 6),
      },
    ]
  }

  const items: ExperienceItem[] = []

  for (const c of candidates.slice(0, 12)) {
    const context = lines.slice(Math.max(0, c.idx - 2), Math.min(lines.length, c.idx + 3))
    const roleOrg = context.find((l) => looksLikeRoleOrg(l) && l !== c.line) ?? c.line

    // naive split
    const parts = roleOrg.split(/[-—–|•]/).map((p) => p.trim()).filter(Boolean)

    const role = parts[0] || roleOrg
    const org = parts[1] || ''

    const details = context
      .filter((l) => l !== roleOrg && l !== c.line)
      .slice(0, 2)

    items.push({ date: c.yearSpan!, role, org, details })
  }

  // de-dupe by date+role
  const uniq: ExperienceItem[] = []
  const seen = new Set<string>()
  for (const it of items) {
    const k = `${it.date}|${it.role}`
    if (seen.has(k)) continue
    seen.add(k)
    uniq.push(it)
  }

  return uniq
}
