import type { Message } from '@/types/messages'
import { API } from '@/Api'

function handleDownloadsResponse(response: any) {
  console.log('Download response:', response)
  try {
    if (!response || !response.status || response.status !== 200) {
      throw new Error('Failed to download artifacts')
    }

    // Flask sets Content-Disposition: attachment; filename=...
    const blob = response.data

    // Extract filename from headers if available
    const disposition = response.headers['content-disposition']
    let filename = 'download'
    if (disposition && disposition.includes('filename=')) {
      filename = disposition.split('filename=')[1].replace(/['"]/g, '')
    }

    // Create a temporary link and trigger the download
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = filename
    document.body.appendChild(a)
    a.click()
    a.remove()
    URL.revokeObjectURL(url)
  } catch (err) {
    console.error('Download failed:', err)
  }
}
export async function downloadArtifacts(msgId?: string, artId?: string, artIndex?: number) {
  console.log('Downloading artifacts for msgId:', msgId, 'artId:', artId, 'artIndex:', artIndex)
  if (!msgId || !artId) return
  try {
    const response = await API.downloadArtifactsById(msgId, artId, artIndex ?? 0)
    handleDownloadsResponse(response)
  } catch (err) {
    console.error('Download failed:', err)
  }
}
export async function downloadCsvsFromMsg(msg: Message) {
  if (!msg.id) return
  try {
    const response = await API.downloadArtifacts(msg.id)
    handleDownloadsResponse(response)
  } catch (err) {
    console.error('Download failed:', err)
  }
}
