const FILE_EXT_RE =
  /\.(zip|7z|rar|tar|gz|bz2|xz|dmg|pkg|exe|msi|iso|torrent|pdf|mp4|mkv|mp3|flac|apk|deb|rpm|ipa|img|bin)(?:$|[?#])/i
const WEB_DOC_CONTENT_TYPE_RE =
  /^(text\/html|text\/plain|application\/json|application\/javascript|application\/xml|text\/xml)/i
const DOWNLOAD_HINT_PATH_RE = /(^|\/)(download|downloads|dl|get|file|files|attachment|attachments)(\/|$)/i

function tryUrl(raw: string, base?: string): URL | null {
  try {
    return new URL(raw, base)
  } catch {
    return null
  }
}

export function normalizeUrl(raw: string, base?: string): string {
  const parsed = tryUrl(raw, base)
  return parsed ? parsed.toString() : String(raw || '')
}

export function hasLikelyFileExtension(rawUrl: string, base?: string): boolean {
  const parsed = tryUrl(rawUrl, base)
  if (!parsed) return FILE_EXT_RE.test(String(rawUrl || ''))
  return FILE_EXT_RE.test(parsed.pathname || '')
}

function decodeBase64UrlSafe(value: string): string {
  const normalized = String(value || '').replace(/-/g, '+').replace(/_/g, '/')
  try {
    return atob(normalized)
  } catch {
    return ''
  }
}

function looksOpaqueDownloadPath(pathname: string): boolean {
  if (!DOWNLOAD_HINT_PATH_RE.test(pathname)) return false
  const segments = String(pathname || '').split('/').filter(Boolean)
  const last = segments[segments.length - 1] || ''
  if (!last || last.includes('.')) return false
  return /^[a-z0-9_-]{12,}$/i.test(last)
}

function hasDownloadHintFromQuery(parsed: URL): boolean {
  const params = parsed.searchParams
  const goLink = params.get('golink')
  if (goLink) {
    const decoded = decodeBase64UrlSafe(goLink)
    if (decoded && FILE_EXT_RE.test(decoded)) return true
  }

  const filename = params.get('filename') || params.get('file') || params.get('name') || params.get('out')
  if (filename && FILE_EXT_RE.test(filename)) return true
  if (params.has('attachment') || params.has('download')) return true
  return false
}

export function isLikelyDownloadUrl(rawUrl: string, base?: string): boolean {
  const parsed = tryUrl(rawUrl, base)
  if (!parsed) return false
  if (!['http:', 'https:', 'ftp:'].includes(parsed.protocol)) return false

  if (hasLikelyFileExtension(parsed.toString())) return true
  if (hasDownloadHintFromQuery(parsed)) return true
  if (looksOpaqueDownloadPath(parsed.pathname || '')) return true
  return false
}

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

  const contentDisposition = getHeader('content-disposition').toLowerCase()
  const contentType = getHeader('content-type').toLowerCase()

  if (contentDisposition.includes('attachment')) return true
  if (hasLikelyFileExtension(details.url || '')) return true
  if (!contentType) return false
  if (WEB_DOC_CONTENT_TYPE_RE.test(contentType)) return false

  return contentType.startsWith('application/') || contentType.startsWith('audio/') || contentType.startsWith('video/')
}
