import { useTmdbMovie, useTmdbTvShow, useTmdbCollection } from './use-tmdb'
import { useWikidataAwards, useWikidataLocations, useWikiResolve, useWikiSection } from './use-external'
import type { TmdbMovie, TmdbTvShow } from '../api/tmdb'

/**
 * Merged shape that lets call sites access both movie and TV fields without
 * rediscriminating the union at every read. The actual loaded data is one
 * of TmdbMovie or TmdbTvShow at runtime - this Partial intersection is the
 * lowest-friction read shape.
 */
export type TmdbDetailData = Partial<TmdbMovie> & Partial<TmdbTvShow>

interface Args {
  kind: 'movie' | 'tv' | null
  tmdbId: number | string | null | undefined
}

/**
 * Bundles the TMDB-side enrichment used by both DetailPage and
 * TmdbDetailPage: the primary movie/tv record, the collection (if the
 * movie is part of one), the Wikidata awards + filming locations, and the
 * Wikipedia "Production" section. Each consumer can read what it needs;
 * unused fields stay idle (React Query gates on `enabled` per hook so
 * they're free when not consumed).
 */
export function useTmdbDetailEnrichment({ kind, tmdbId }: Args) {
  const numericId = tmdbId != null ? Number(tmdbId) : null
  const validId = numericId != null && Number.isFinite(numericId) ? numericId : null

  const movie = useTmdbMovie(kind === 'movie' ? validId : null)
  const tv = useTmdbTvShow(kind === 'tv' ? validId : null)
  const data = (kind === 'movie' ? movie.data : tv.data) as TmdbDetailData | undefined
  const isLoading = kind === 'movie' ? movie.isLoading : tv.isLoading

  const collectionId = movie.data?.belongs_to_collection?.id
  const collection = useTmdbCollection(collectionId)

  const wikidataId = data?.external_ids?.wikidata_id || null
  const awards = useWikidataAwards(wikidataId)
  const locations = useWikidataLocations(wikidataId)

  const titleForWiki = data?.title || data?.name
  const yearForWiki = (data?.release_date || data?.first_air_date || '').slice(0, 4)
  const wikiTitle = useWikiResolve(
    titleForWiki && yearForWiki ? `${titleForWiki} ${yearForWiki}` : titleForWiki,
    !!titleForWiki,
  )
  const wikiProduction = useWikiSection(wikiTitle.data?.title || null, 'Production')

  return {
    movie,
    tv,
    data,
    isLoading,
    collection,
    awards,
    locations,
    wikiTitle,
    wikiProduction,
  }
}
