import { useQuery } from '@tanstack/react-query'
import { getMediaSegmentsApi, jellyfinClient } from '../../api/jellyfin'
import { debugLog } from '../../lib/log'

export type SegmentLike = {
  Type: 'Intro' | 'Outro' | 'Recap' | 'Preview' | 'Commercial' | 'Unknown'
  StartTicks: number
  EndTicks: number
}

const TICKS_PER_SECOND = 10_000_000

async function tryJsonFetch(url: string, token: string): Promise<any | null> {
  try {
    const res = await fetch(url, {
      headers: { 'X-MediaBrowser-Token': token },
    })
    if (!res.ok) {
      debugLog('[segments] GET', url, '->', res.status)
      return null
    }
    const text = await res.text()
    debugLog('[segments] GET', url, '->', res.status, 'body:', text)
    if (!text) return null
    try {
      return JSON.parse(text)
    } catch {
      return null
    }
  } catch (err) {
    debugLog('[segments] GET', url, 'threw', err)
    return null
  }
}

function pluginPayloadToSegments(data: any): SegmentLike[] {
  if (!data) return []
  const out: SegmentLike[] = []
  if (data.Valid && Number.isFinite(data.IntroStart) && Number.isFinite(data.IntroEnd) && data.IntroEnd > data.IntroStart) {
    out.push({
      Type: 'Intro',
      StartTicks: Math.floor(Number(data.IntroStart) * TICKS_PER_SECOND),
      EndTicks: Math.floor(Number(data.IntroEnd) * TICKS_PER_SECOND),
    })
  }
  if (data.Intro && Number.isFinite(data.Intro.Start) && Number.isFinite(data.Intro.End) && data.Intro.End > data.Intro.Start) {
    out.push({
      Type: 'Intro',
      StartTicks: Math.floor(Number(data.Intro.Start) * TICKS_PER_SECOND),
      EndTicks: Math.floor(Number(data.Intro.End) * TICKS_PER_SECOND),
    })
  }
  if (data.Credits && Number.isFinite(data.Credits.Start) && Number.isFinite(data.Credits.End) && data.Credits.End > data.Credits.Start) {
    out.push({
      Type: 'Outro',
      StartTicks: Math.floor(Number(data.Credits.Start) * TICKS_PER_SECOND),
      EndTicks: Math.floor(Number(data.Credits.End) * TICKS_PER_SECOND),
    })
  }
  if (Array.isArray(data.Items)) {
    for (const it of data.Items) addSegment(out, it)
  }
  if (Array.isArray(data)) {
    for (const it of data) addSegment(out, it)
  }
  return out
}

function addSegment(out: SegmentLike[], it: any) {
  if (!it?.Type) return
  const startTicks = Number(it.StartTicks ?? 0)
  const endTicks = Number(it.EndTicks ?? 0)
  if (endTicks <= startTicks) return
  out.push({
    Type: it.Type as SegmentLike['Type'],
    StartTicks: startTicks,
    EndTicks: endTicks,
  })
}

export function useMediaSegments(itemId?: string) {
  const api = jellyfinClient.getApi()
  return useQuery<SegmentLike[]>({
    queryKey: ['jellyfin', 'media-segments', itemId],
    queryFn: async () => {
      if (!api || !itemId) return []
      const auth = jellyfinClient.getAuthState()
      if (!auth) return []
      const { serverUrl, token } = auth

      const urls = [
        `${serverUrl}/MediaSegments/${itemId}`,
        `${serverUrl}/Episode/${itemId}/IntroSkipperSegments`,
        `${serverUrl}/Episode/${itemId}/Timestamps`,
        `${serverUrl}/Episode/${itemId}/IntroTimestamps/v1`,
        `${serverUrl}/Episode/${itemId}/IntroTimestamps`,
      ]

      for (const url of urls) {
        const data = await tryJsonFetch(url, token)
        if (!data) continue
        const segments = pluginPayloadToSegments(data)
        if (segments.length > 0) {
          debugLog('[segments] resolved from', url, segments)
          return segments
        }
      }

      try {
        const res = await getMediaSegmentsApi(api).getItemSegments({ itemId })
        const items = (res.data.Items || []).map(s => ({
          Type: (s.Type || 'Unknown') as SegmentLike['Type'],
          StartTicks: Number(s.StartTicks ?? 0),
          EndTicks: Number(s.EndTicks ?? 0),
        }))
        if (items.length > 0) {
          debugLog('[segments] resolved via SDK', items)
          return items
        }
      } catch (err) {
        debugLog('[segments] SDK call failed', err)
      }

      debugLog('[segments] no data from any source for', itemId)
      return []
    },
    enabled: !!api && !!itemId,
    staleTime: 60 * 60 * 1000,
  })
}
