export type MediaKind = 'mp4' | 'm3u8' | 'm3u' | 'hls' | 'unknown'

export type MediaCandidate = {
  id: string
  url: string
  kind: MediaKind
  tabId: number
  pageUrl: string
  referer: string
  contentType: string
  detectedAt: number
}

function getHeader(details: any, name: string): string {
  const headers = Array.isArray(details?.responseHeaders) ? details.responseHeaders : []
  const lower = name.toLowerCase()
  const found = headers.find((h: any) => String(h?.name || '').toLowerCase() === lower)
  return String(found?.value || '')
}

function byContentType(contentType: string): MediaKind {
  const type = contentType.toLowerCase()
  if (!type) return 'unknown'
  if (type.includes('application/vnd.apple.mpegurl')) return 'm3u8'
  if (type.includes('application/x-mpegurl')) return 'm3u8'
  if (type.includes('audio/mpegurl')) return 'm3u8'
  if (type.includes('video/mp4')) return 'mp4'
  if (type.includes('application/octet-stream') && type.includes('m3u8')) return 'm3u8'
  if (type.includes('hls')) return 'hls'
  return 'unknown'
}

function byUrl(url: string): MediaKind {
  const lower = String(url || '').toLowerCase()
  if (lower.includes('.m3u8')) return 'm3u8'
  if (lower.includes('.m3u')) return 'm3u'
  if (lower.includes('.mp4')) return 'mp4'
  if (lower.includes('m3u8')) return 'm3u8'
  if (lower.includes('hls')) return 'hls'
  return 'unknown'
}

export function detectMediaKind(url: string, contentType: string): MediaKind {
  const fromType = byContentType(contentType)
  if (fromType !== 'unknown') return fromType
  return byUrl(url)
}

export function shouldCaptureMediaResponse(details: any): boolean {
  if (!details?.url) return false
  const method = String(details?.method || '').toUpperCase()
  if (method && method !== 'GET') return false

  const statusCode = Number(details?.statusCode || 0)
  if (statusCode > 0 && (statusCode < 200 || statusCode > 299)) return false

  const type = String(details?.type || '')
  if (!['xmlhttprequest', 'media', 'other', 'main_frame', 'sub_frame', 'fetch'].includes(type)) {
    return false
  }

  const contentType = getHeader(details, 'content-type')
  const kind = detectMediaKind(details.url, contentType)
  return kind !== 'unknown'
}

export function makeMediaCandidate(details: any, referer = ''): MediaCandidate {
  const contentType = getHeader(details, 'content-type')
  const url = String(details?.url || '')
  const kind = detectMediaKind(url, contentType)
  const tabId = Number.isInteger(details?.tabId) ? Number(details.tabId) : -1
  const now = Date.now()

  return {
    id: `${now}:${tabId}:${kind}:${url}`,
    url,
    kind,
    tabId,
    pageUrl: String(details?.documentUrl || details?.initiator || ''),
    referer: String(referer || details?.documentUrl || details?.initiator || ''),
    contentType,
    detectedAt: now,
  }
}

export function mediaFingerprint(url: string): string {
  try {
    const parsed = new URL(url)
    return `${parsed.protocol}//${parsed.host}${parsed.pathname}`.toLowerCase()
  } catch {
    return String(url || '').toLowerCase()
  }
}
