#ifndef DOWNLOADS_DOWNLOAD_MANAGER_H
#define DOWNLOADS_DOWNLOAD_MANAGER_H

#include "core/profile.h"
#include <gtk/gtk.h>
#include <webkit2/webkit2.h>

// Download states
typedef enum {
  DOWNLOAD_STATE_PENDING,
  DOWNLOAD_STATE_DOWNLOADING,
  DOWNLOAD_STATE_PAUSED,
  DOWNLOAD_STATE_COMPLETED,
  DOWNLOAD_STATE_FAILED,
  DOWNLOAD_STATE_CANCELLED
} DownloadState;

// Download part for multi-part downloads
typedef struct {
  size_t part_number;
  size_t start_byte;
  size_t end_byte;
  size_t downloaded;
  char *temp_file;
  gboolean completed;
  GThread *thread;
} DownloadPart;

// Main download structure
typedef struct {
  char *url;
  char *destination;
  char *filename;
  WebKitDownload *webkit_download; // For WebKit-initiated downloads

  size_t total_size;
  size_t downloaded;
  DownloadState state;

  // Multi-part download
  int num_parts;
  DownloadPart **parts;

  // Control
  GMutex mutex;
  gboolean cancel_requested;
  gboolean pause_requested;

  // Stats
  double speed;           // bytes per second
  double eta;             // seconds remaining
  size_t last_downloaded; // for speed calc
  gint64 last_time;       // for speed calc

  // Progress callback
  void (*progress_callback)(gpointer download, gpointer user_data);
  gpointer user_data;
} Download;

/**
 * Initialize download manager
 */
void download_manager_init(void);

/**
 * Start a download with multi-part support
 * @param url URL to download
 * @param destination Destination file path
 * @param num_parts Number of parts (1, 2, 4, 8, 16, 32)
 * @return Download* or NULL on failure
 */
Download *download_start(const char *url, const char *destination,
                         int num_parts);

/**
 * Start a WebKit-initiated download
 * @param webkit_download WebKitDownload object
 * @param num_parts Number of parts
 * @return Download* or NULL on failure
 */
Download *download_start_webkit(WebKitDownload *webkit_download, int num_parts);

/**
 * Pause a download
 * @param download Download to pause
 */
void download_pause(Download *download);

/**
 * Resume a paused download
 * @param download Download to resume
 */
void download_resume(Download *download);

/**
 * Cancel a download
 * @param download Download to cancel
 */
void download_cancel(Download *download);

/**
 * Free download resources
 * @param download Download to free
 */
void download_free(Download *download);

/**
 * Get all active downloads
 * @return GList* of Download*
 */
GList *download_manager_get_downloads(void);

#endif
