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)
    .filter((l) => l.length > 3 && !l.match(/^[\d\W]+$/))
}

function pickYearSpan(line: string): string | null {
  const years = line.match(yearRe)
  if (!years?.length) return null
  
  // Match patterns like "2016 - 2024", "2016–2024", "2016-2024"
  const span = line.match(/(19\d{2}|20\d{2})\s*[-–—]\s*(19\d{2}|20\d{2}|Present|Current|Now)/i)
  if (span) return span[0].replace(/\s+/g, ' ').trim()
  
  // Match single year with context
  if (years.length >= 1) return years[0]
  return null
}

function looksLikeRoleOrg(line: string): boolean {
  const keywords = [
    'counselor', 'therapist', 'clinician', 'supervisor', 'director',
    'coordinator', 'intern', 'case manager', 'assistant', 'specialist',
    'practitioner', 'consultant', 'educator', 'facilitator'
  ]
  const lc = line.toLowerCase()
  return keywords.some(kw => lc.includes(kw)) && lc.length >= 6
}

function looksLikeOrg(line: string): boolean {
  const orgIndicators = [
    'center', 'clinic', 'hospital', 'health', 'services', 'inc', 'llc',
    'university', 'college', 'institute', 'foundation', 'agency',
    'department', 'corporation', 'group', 'practice'
  ]
  const lc = line.toLowerCase()
  return orgIndicators.some(ind => lc.includes(ind)) || line.length > 15
}

export async function parseResumeDocx(url: string): Promise<ExperienceItem[]> {
  try {
    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({
      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) {
      return []
    }

    const items: ExperienceItem[] = []
    const seen = new Set<string>()

    for (const c of candidates) {
      // Get context around the date line
      const contextStart = Math.max(0, c.idx - 3)
      const contextEnd = Math.min(lines.length, c.idx + 4)
      const context = lines.slice(contextStart, contextEnd)
      
      // Find role - look for lines that look like job titles
      let role = ''
      let org = ''
      const details: string[] = []
      
      for (let i = 0; i < context.length; i++) {
        const line = context[i]
        if (line === c.line) continue
        
        if (!role && looksLikeRoleOrg(line)) {
          role = line
          // Check next line for organization
          if (i + 1 < context.length) {
            const nextLine = context[i + 1]
            if (nextLine !== c.line && (looksLikeOrg(nextLine) || !looksLikeRoleOrg(nextLine))) {
              org = nextLine
            }
          }
        } else if (!org && looksLikeOrg(line) && !looksLikeRoleOrg(line)) {
          org = line
        } else if (line.length > 20 && !line.match(/^\d{4}/)) {
          // Likely a description/detail line
          details.push(line)
        }
      }
      
      // If no role found, use a nearby non-date line
      if (!role) {
        role = context.find(l => l !== c.line && l.length > 5) || 'Professional Position'
      }
      
      // Clean up role/org
      role = role.replace(/^[-•\s]+/, '').trim()
      org = org.replace(/^[-•\s]+/, '').trim()
      
      // Skip duplicates
      const key = `${c.yearSpan}|${role}`
      if (seen.has(key)) continue
      seen.add(key)
      
      items.push({
        date: c.yearSpan!,
        role: role,
        org: org,
        details: details.slice(0, 3) // Limit to 3 details
      })
    }

    return items
  } catch (err) {
    console.error('Resume parsing error:', err)
    throw err
  }
}
