import { STATE_INFO_TOPIC_KEYS, type StateInfoSection, type StateInfoTopicKey, type StateProvisions } from './state-info'

export interface StateCatalogInfo {
  stateCode: string
  stateName: string
  syncedAt: string | null
  information: StateProvisions
  provisions: StateProvisions
  provisionUrls: string[]
  provisionSyncStatus: string | null
}

export function emptyStateTopics(): StateProvisions {
  return Object.fromEntries(STATE_INFO_TOPIC_KEYS.map((key) => [key, []])) as unknown as StateProvisions
}

const FIELDS: Array<[StateInfoTopicKey, string, string[]]> = [
  ['travel', 'Night travel', ['night_travel', 'night_traver']],
  ['travel', 'Operating time', ['operating_time']],
  ['travel', 'Speed limit', ['speed_limit']],
  ['travel', 'Restricted travel', ['restricted_travel']],
  ['escort', 'Escorts', ['escorts']],
  ['escort', 'Interstate escorts', ['interstate_escort']],
  ['escort', 'Lane requirements', ['lane_escort_req']],
  ['escort', 'Police escorts', ['police_escort_req']],
  ['permit_limits', 'Permit limits', ['permit_limits']],
  ['legal_limits', 'Legal dimensions', ['legal_dimensions']],
  ['legal_limits', 'Legal limits', ['legal_limits']],
  ['legal_limits', 'Maximum weight per axle', ['max_weight_per_axle']],
  ['signs', 'Signs, flags & lights', ['signs_flags_lights']],
  ['superloads', 'Superloads', ['superloads']],
  ['superloads', 'Superload thresholds', ['superload_trigger']],
  ['superloads', 'Route survey', ['route_survey']],
  ['miscellaneous', 'Miscellaneous', ['miscellaneous']],
  ['miscellaneous', 'CSI reference information', ['csi_book_data']],
  ['state_details', 'State website', ['state_website']],
  ['state_details', 'State phone', ['state_phone']],
  ['state_details', 'State email', ['state_email']],
  ['state_details', 'Time zone', ['time_zone']],
  ['state_details', 'Total permits', ['total_permit']],
  ['pricing', 'Pricing', ['pricing']],
  ['pricing', 'Oversize permit price', ['od_permit_price']],
  ['pricing', 'Overweight permit price', ['ow_permit_price']],
  ['pricing', 'Permitting service fee', ['service_fee']],
]

/** Display source text as text, never execute provider HTML. */
function clean(value: string): string {
  return value.replace(/\\n/g, '\n').replace(/\\"/g, '"').replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '')
    .replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, '')
    .replace(/<(?:br\s*\/?|\/p|\/div|\/li)>/gi, '\n')
    .replace(/<[^>]*>/g, '')
    .replace(/&nbsp;/gi, ' ').replace(/&amp;/gi, '&').replace(/&lt;/gi, '<').replace(/&gt;/gi, '>')
    .replace(/&quot;/gi, '"').replace(/&#(?:39|x27);/gi, "'")
    .replace(/&#(\d+);/g, (_, n: string) => { const code = Number(n); return code <= 0x10ffff ? String.fromCodePoint(code) : '' })
    .trim()
}

function decode(value: unknown): unknown {
  if (typeof value !== 'string') return value
  try { return JSON.parse(value) } catch { return value }
}

/** Only public operational fields are selected; the full catalog row never leaves the server. */
function sections(value: unknown, heading?: string, depth = 0): StateInfoSection[] {
  if (depth > 6 || value == null) return []
  const decoded = decode(value)
  if (typeof decoded === 'string' || typeof decoded === 'number' || typeof decoded === 'boolean') {
    const detail = clean(typeof decoded === 'boolean' ? (decoded ? 'Yes' : 'No') : String(decoded))
    return detail ? [{ heading, items: [{ detail }] }] : []
  }
  if (Array.isArray(decoded)) return decoded.flatMap((item) => sections(item, heading, depth + 1))
  if (typeof decoded === 'object') {
    return Object.entries(decoded as Record<string, unknown>)
      .filter(([key]) => !/password|username|secret|token|credential|auth|cookie|session/i.test(key))
      .flatMap(([key, item]) => sections(item, heading ? `${heading} · ${clean(key)}` : clean(key), depth + 1))
  }
  return []
}

/** Provision URLs may be plain text, HTML, arrays or JSON encoded with escaped slashes. */
export function provisionDocumentUrls(value: unknown): string[] {
  const text = (typeof value === 'string' ? value : JSON.stringify(value ?? ''))
    .replace(/\\\//g, '/').replace(/&amp;/g, '&')
  const urls = text.match(/https?:\/\/[^\s<>"'\\\]]+/gi) ?? []
  return [...new Set(urls.filter((url) => {
    try { const parsed = new URL(url); return ['http:', 'https:'].includes(parsed.protocol) && !parsed.username && !parsed.password } catch { return false }
  }))]
}

function provisionTopic(label: string): StateInfoTopicKey {
  if (/price|pricing|fee/i.test(label)) return 'pricing'
  if (/contact|website|phone|email|time.?zone/i.test(label)) return 'state_details'
  if (/escort/i.test(label)) return 'escort'
  if (/legal.*(?:dimension|limit)|axle/i.test(label)) return 'legal_limits'
  if (/superload|overload|survey/i.test(label)) return 'superloads'
  if (/permit.*limit|special.*permit/i.test(label)) return 'permit_limits'
  if (/sign|flag|light/i.test(label)) return 'signs'
  if (/travel|operating|speed|weekend|holiday|curfew|weather/i.test(label)) return 'travel'
  return 'miscellaneous'
}

export function normalizeStateCatalog(row: {
  state_code: string; state_name: string; synced_at?: string; details: Record<string, unknown>
}): StateCatalogInfo {
  const information = emptyStateTopics()
  for (const [topic, heading, aliases] of FIELDS) {
    const seen = new Set<string>()
    for (const key of aliases) {
      const groups = sections(row.details[key], heading)
      const content = JSON.stringify(groups)
      if (seen.has(content)) continue
      seen.add(content)
      information[topic].push(...groups)
    }
  }
  const provisions = emptyStateTopics()
  const decoded = decode(row.details.provision_info)
  if (decoded && typeof decoded === 'object' && !Array.isArray(decoded)) {
    for (const [heading, value] of Object.entries(decoded as Record<string, unknown>)) {
      if (/password|username|secret|token|credential|auth/i.test(heading)) continue
      provisions[provisionTopic(heading)].push(...sections(value, clean(heading)))
    }
  } else {
    provisions.miscellaneous.push(...sections(decoded, 'Provisions'))
  }
  return {
    stateCode: row.state_code, stateName: row.state_name, syncedAt: row.synced_at ?? null,
    information, provisions, provisionUrls: provisionDocumentUrls(row.details.provision),
    provisionSyncStatus: typeof row.details.provision_sync_status === 'string' ? row.details.provision_sync_status : null,
  }
}
