import { useDownloads } from '../stores/downloads-store'

/**
 * Download a Jellyfin stream to local storage as a Blob URL.
 *
 * Note: persistent disk storage in the Tauri build would require the
 * tauri-plugin-fs plugin, which is not currently included. For now both
 * browser and Tauri builds cache downloads as in-memory Blob URLs.
 */
export async function startDownload(args: {
  itemId: string
  name: string
  posterUrl?: string | null
  streamUrl: string
  subtitleUrl?: string | null
}) {
  const { itemId, name, posterUrl, streamUrl, subtitleUrl } = args
  const store = useDownloads.getState()

  // Don't re-queue if already active
  if (store.getByItemId(itemId)) {
    return
  }

  const dl = store.add({ itemId, name, posterUrl, streamUrl, subtitleUrl })

  try {
    store.update(dl.id, { status: 'downloading', progress: 0 })

    const response = await fetch(streamUrl)
    if (!response.ok || !response.body) {
      throw new Error(`Download failed: ${response.status}`)
    }

    const contentLength = Number(response.headers.get('content-length')) || 0
    const reader = response.body.getReader()
    const chunks: Uint8Array[] = []
    let received = 0

    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      chunks.push(value)
      received += value.length
      if (contentLength > 0) {
        store.update(dl.id, {
          progress: Math.min(100, Math.round((received / contentLength) * 100)),
        })
      }
    }

    const blob = new Blob(chunks as BlobPart[])
    const objectUrl = URL.createObjectURL(blob)
    store.update(dl.id, {
      status: 'done',
      progress: 100,
      sizeBytes: received,
      localPath: objectUrl,
    })
  } catch (err: any) {
    store.update(dl.id, {
      status: 'error',
      error: err?.message || 'Download failed',
    })
  }
}
