import { STATE_INFO_TOPIC_META, type StateInfoTopicKey } from '@/lib/domain/state-info'
import { getStateProvisions } from '@/lib/demo/state-info-data'

/**
 * The flat, one-paragraph-per-topic view of the sample state knowledge.
 *
 * The screens moved to the structured version (`StateInfoView`), but the
 * moderation console and the demo agent still want a sentence they can quote,
 * so this flattens the same sections rather than keeping a second copy of the
 * content to drift (2026-09-25).
 */

export const STATE_INFO_TOPICS = [
  'Travel info',
  'Escort info',
  'Permit limits',
  'Legal limits',
  'Signs & more',
  'Superloads',
] as const

export type StateInfoTopic = (typeof STATE_INFO_TOPICS)[number]

type StateInfo = Record<StateInfoTopic, string>

/** The legacy label for each structured topic, in the same order. */
const LABEL: Record<StateInfoTopicKey, StateInfoTopic> = {
  travel: 'Travel info',
  escort: 'Escort info',
  permit_limits: 'Permit limits',
  legal_limits: 'Legal limits',
  signs: 'Signs & more',
  superloads: 'Superloads',
}

/** "Over 14′ wide — 2 escorts." reads as one sentence again. */
function flatten(sections: ReturnType<typeof getStateProvisions>[StateInfoTopicKey]): string {
  return sections
    .flatMap((s) => {
      const lead = s.note ? [s.note] : []
      return [...lead, ...s.items.map((i) => (i.term ? `${i.term} — ${i.detail}` : i.detail))]
    })
    .join(' ')
}

export function getStateInfo(code: string): StateInfo {
  const provisions = getStateProvisions(code)
  const out = {} as StateInfo
  for (const t of STATE_INFO_TOPIC_META) out[LABEL[t.key]] = flatten(provisions[t.key])
  return out
}
