/** A demand_grade row, expanded one row per category_id it belongs to. */
export interface DemandGradeItem {
  id: number
  demand_name: string
  category_id: number
  grade: string
  score: number | null
  reason: string | null
  /** JSON-encoded string array of source strategies, e.g. '["新热事件","逐月"]'. */
  strategies: string | null
  biz_dt: string
}

export interface DemandGradeResponse {
  items: DemandGradeItem[]
}

export interface DemandExpansionPoint {
  expanded_text: string
  point_type: 'inspiration' | 'purpose' | 'key'
  point_desc: string | null
  reason: string
}

export interface DemandVideoItem {
  vid: string
  title: string | null
  expansion_points: DemandExpansionPoint[]
}

export interface DemandGradeVideosResponse {
  demand_grade_id: number
  demand_name: string
  biz_dt: string
  category_ids: number[]
  grade: string
  strategies: string[]
  expansion_status: 'finished' | 'failed' | string | null
  expansion_saved_count: number
  videos: DemandVideoItem[]
}

/** category_id → demands belonging to that category */
export type DemandsByCategory = Record<number, DemandGradeItem[]>

export function groupDemandsByCategory(items: DemandGradeItem[]): DemandsByCategory {
  const map: DemandsByCategory = {}
  for (const item of items) {
    const key = item.category_id
    if (!map[key]) map[key] = []
    map[key].push(item)
  }
  return map
}

/** Parse the JSON-encoded strategies string into a plain string array. */
export function parseStrategies(raw: string | null | undefined): string[] {
  if (!raw) return []
  try {
    const parsed = JSON.parse(raw)
    return Array.isArray(parsed) ? parsed.map((s) => String(s)) : []
  } catch {
    return []
  }
}

export const GRADE_ORDER = ['S', 'A', 'B', 'C', 'D'] as const
export type DemandGradeLevel = (typeof GRADE_ORDER)[number]

export function gradeRank(grade: string | null | undefined): number {
  if (!grade) return GRADE_ORDER.length
  const idx = GRADE_ORDER.indexOf(grade.toUpperCase() as DemandGradeLevel)
  return idx === -1 ? GRADE_ORDER.length : idx
}
