import re
from typing import Any, Optional


class GenerationResponse:
    """Response from an async generation request."""

    def __init__(self, data: dict):
        self.data = data or {}
        self.task_id: Optional[str] = (
            self.data.get("task_id")
            or self.data.get("taskId")
            or self.data.get("id")
            or None
        )


class TaskStatus:
    """Status of an async generation task."""

    def __init__(self, data: dict):
        self.data = data or {}
        self.id: str = self.data.get("id", "")
        self.action: str = self.data.get("action", "")
        self.status: str = self.data.get("status", "")
        self.completion: str = self.data.get("completion", "")
        self.created_at: str = self.data.get("created_at", "")
        self.updated_at: str = self.data.get("updated_at", "")
        self.progress: str = self.data.get("progress", "")
        self.fail_reason: str = self.data.get("fail_reason", "")
        self.result: Any = self.data.get("result", None)

    def is_completed(self) -> bool:
        return self.status == "SUCCESS"

    def is_failed(self) -> bool:
        return self.status == "FAILURE"

    def is_processing(self) -> bool:
        return self.status in ("PENDING", "PROCESSING", "RUNNING", "QUEUED")

    @property
    def progress_percent(self) -> int:
        if not self.progress:
            return 0
        match = re.search(r"(\d+)", self.progress)
        return int(match.group(1)) if match else 0
