/**
 * The trip carrier, validated from its permits (Nash, 2026-10-07, item 3).
 *
 * When at least 50% of the trip's readable permits name one carrier, that
 * carrier is validated. If no carrier has a majority, the unique carrier
 * named on the most readable permits is validated; only a tie for most stays
 * in 'needs_confirmation'. Carriers match by USDOT number first, then by
 * normalized name. Defaults until Nash answers the remaining edge cases
 * (Workspace CTO file of 2026-10-08):
 *   - tie for most readings → 'needs_confirmation' (nothing is picked arbitrarily)
 *   - no permit names a carrier → 'unverified' (the selected carrier stays)
 *   - a name-only reading that matches two different carriers counts as unreadable
 * Pure functions; attaching, replacing and locking the carrier is the caller's job.
 */
export interface CarrierEvidence { name: string | null; usdot: string | null; mc: string | null }

export type CarrierValidation =
  | { status: 'validated'; carrier: CarrierEvidence; changed: boolean; readable: number; total: number }
  | { status: 'needs_confirmation'; candidates: CarrierEvidence[]; readable: number; total: number }
  | { status: 'unverified'; readable: 0; total: number }

const record = (v: unknown): Record<string, unknown> => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : {})
const text = (v: unknown): string | null => (typeof v === 'string' || typeof v === 'number') && String(v).trim() ? String(v).trim() : null
const digits = (v: unknown): string | null => { const t = text(v)?.replace(/\D/g, ''); return t ? t.replace(/^0+(?=\d)/, '') : null }

function evidenceFrom(info: unknown): CarrierEvidence | null {
  const r = record(info)
  const ev = { name: text(r.name ?? r.company_name ?? r.carrier_name), usdot: digits(r.dot ?? r.usdot ?? r.dot_number ?? r.usdot_number), mc: digits(r.mc ?? r.mc_number) }
  return ev.name || ev.usdot ? ev : null
}

/** The carrier the Brain read from one permit, from the stored reading (permits.extraction). */
export function carrierFromReading(extraction: unknown): CarrierEvidence | null {
  const raw = record(record(extraction).raw)
  const candidates: unknown[] = [record(raw.order_info).carrier_info, record(extraction).carrier_info]
  for (const response of Array.isArray(raw.permit_responses) ? raw.permit_responses : []) candidates.push(record(record(response).llm_response).carrier_info)
  for (const c of candidates) { const ev = evidenceFrom(c); if (ev) return ev }
  return null
}

const SUFFIXES = new Set(['LLC', 'INC', 'INCORPORATED', 'CORP', 'CORPORATION', 'CO', 'COMPANY', 'LTD', 'LIMITED', 'LP', 'LLP', 'THE'])

/** Case, punctuation, "&" vs "and" and company suffixes don't matter: "A.B.C. Trucking, LLC" = "ABC TRUCKING". */
export function normalizeCarrierName(name: string): string {
  return name.toUpperCase().replace(/&/g, ' AND ').replace(/[.,']/g, '').replace(/[^A-Z0-9]+/g, ' ')
    .split(' ').filter((w) => w && !SUFFIXES.has(w)).join(' ')
}

/** Every name a carrier goes by: the full name and each side of "DBA". */
function nameKeys(name: string | null): Set<string> {
  if (!name) return new Set()
  const parts = [name, ...name.split(/\bD\/?B\/?A\b/i)]
  return new Set(parts.map(normalizeCarrierName).filter(Boolean))
}

export function sameCarrier(a: CarrierEvidence, b: CarrierEvidence): boolean {
  if (a.usdot && b.usdot) return a.usdot === b.usdot
  const keysB = nameKeys(b.name)
  return [...nameKeys(a.name)].some((k) => keysB.has(k))
}

export function validateTripCarrier(params: { permits: Array<CarrierEvidence | null>; current: CarrierEvidence | null }): CarrierValidation {
  const total = params.permits.length
  const readings = params.permits.filter((p): p is CarrierEvidence => !!p)
  // Group readings that carry a USDOT number first, then attach name-only readings.
  const groups: CarrierEvidence[][] = []
  for (const ev of readings.filter((r) => r.usdot)) {
    const g = groups.find((members) => members[0].usdot === ev.usdot)
    if (g) g.push(ev); else groups.push([ev])
  }
  let readable = groups.reduce((n, g) => n + g.length, 0)
  for (const ev of readings.filter((r) => !r.usdot)) {
    const matches = groups.filter((members) => members.some((m) => sameCarrier(m, ev)))
    if (matches.length > 1) continue // ambiguous name: counts as unreadable
    if (matches.length === 1) matches[0].push(ev); else groups.push([ev])
    readable++
  }
  if (readable === 0) return { status: 'unverified', readable: 0, total }
  const ranked = [...groups].sort((a, b) => b.length - a.length)
  const top = ranked[0]
  const tie = ranked.length > 1 && ranked[1].length === top.length
  if (tie) {
    return { status: 'needs_confirmation', candidates: ranked.filter((g) => g.length === top.length).map(representative), readable, total }
  }
  const carrier = representative(top)
  return { status: 'validated', carrier, changed: !params.current || !sameCarrier(params.current, carrier), readable, total }
}

/** The most complete reading in a group (USDOT and name preferred). */
function representative(group: CarrierEvidence[]): CarrierEvidence {
  return [...group].sort((a, b) => score(b) - score(a))[0]
}
const score = (e: CarrierEvidence) => (e.usdot ? 2 : 0) + (e.name ? 1 : 0) + (e.mc ? 0.5 : 0)
