/** Best-effort extraction when API payload shapes vary. */

export function rowsFromUnknown(
  data: unknown,
  keys = ['rows', 'students', 'entries'] as const,
): Record<string, unknown>[] {
  if (Array.isArray(data)) return data as Record<string, unknown>[]
  if (!data || typeof data !== 'object') return []
  const o = data as Record<string, unknown>
  for (const k of keys) {
    const v = o[k]
    if (Array.isArray(v)) return v as Record<string, unknown>[]
  }
  return []
}

export function sectionsFromUnknown(data: unknown): Record<string, unknown>[] {
  if (!data || typeof data !== 'object') return []
  const o = data as Record<string, unknown>
  for (const k of ['sections', 'class_sections', 'classes'] as const) {
    const v = o[k]
    if (Array.isArray(v)) return v as Record<string, unknown>[]
  }
  return []
}

export function trackingSectionsFromPayload(data: unknown): {
  title: string
  rows: Record<string, unknown>[]
}[] {
  if (!data || typeof data !== 'object') return []
  const o = data as Record<string, unknown>
  if (Array.isArray(o.sections)) {
    return (o.sections as unknown[]).map((s, i) => {
      const sec = (typeof s === 'object' && s !== null ? s : {}) as Record<string, unknown>
      const title = String(sec.name ?? sec.title ?? sec.class_section_name ?? `Section ${i + 1}`)
      const rows = rowsFromUnknown(sec)
      return { title, rows }
    })
  }
  const flat = rowsFromUnknown(o)
  return flat.length ? [{ title: 'Homework tracking', rows: flat }] : []
}
