# src/data/download_job.py

import time
import uuid


class DownloadJob:
    """
    Representa una descarga en curso.
    Vive en memoria (por ahora).
    """

    def __init__(self):
        self.id = str(uuid.uuid4())

        # Estado del job
        self.status = "created"      # created | downloading | processing | done | cancelled | failed
        self.message = "Inicializando"

        # Progreso
        self.progress = 0            # 0–100
        self.blocks_done = 0
        self.blocks_total = None     # estimado si se conoce

        # Control
        self.cancelled = False

        # Timestamps
        self.created_at = time.time()
        self.updated_at = self.created_at

    def update(
        self,
        *,
        status=None,
        message=None,
        progress=None,
        blocks_done=None,
        blocks_total=None,
    ):
        """
        Actualiza el estado del job.
        """
        if self.cancelled:
            return

        if status is not None:
            self.status = status
        if message is not None:
            self.message = message
        if progress is not None:
            self.progress = int(progress)
        if blocks_done is not None:
            self.blocks_done = int(blocks_done)
        if blocks_total is not None:
            self.blocks_total = int(blocks_total)

        self.updated_at = time.time()

    def cancel(self):
        """
        Marca el job como cancelado.
        El downloader debe respetar esto.
        """
        self.cancelled = True
        self.status = "cancelled"
        self.message = "Descarga cancelada por el usuario"
        self.updated_at = time.time()

    def as_dict(self):
        """
        Representación serializable para la API / UI.
        """
        return {
            "job_id": self.id,
            "status": self.status,
            "message": self.message,
            "progress": self.progress,
            "blocks_done": self.blocks_done,
            "blocks_total": self.blocks_total,
            "cancelled": self.cancelled,
        }
