"""Task data model."""

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime
from typing import Any, Optional


@dataclass
class Task:
    id: str
    requester_id: str
    type: str
    prompt: str
    model: str
    status: str
    credit_budget: int
    research_episode_id: Optional[str] = None
    attempt_index: int = 0
    parent_attempt_id: Optional[str] = None
    task_metadata: dict[str, Any] | None = None
    provider_id: Optional[str] = None
    attempt_count: int = 0
    max_attempts: int = 3
    lease_expires_at: Optional[datetime] = None
    claimed_at: Optional[datetime] = None
    started_at: Optional[datetime] = None
    completed_at: Optional[datetime] = None
    failed_at: Optional[datetime] = None
    last_error: str = ""
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None

    @classmethod
    def from_row(cls, row: dict) -> Task:
        return cls(
            id=row["id"],
            requester_id=row["requester_id"],
            type=row.get("type", "lean_proof_gen"),
            prompt=row["prompt"],
            model=row.get("model", ""),
            status=row["status"],
            credit_budget=row.get("credit_budget", 0),
            research_episode_id=row.get("research_episode_id"),
            attempt_index=row.get("attempt_index", 0),
            parent_attempt_id=row.get("parent_attempt_id"),
            task_metadata=row.get("task_metadata") or {},
            provider_id=row.get("provider_id"),
            attempt_count=row.get("attempt_count", 0),
            max_attempts=row.get("max_attempts", 3),
            lease_expires_at=row.get("lease_expires_at"),
            claimed_at=row.get("claimed_at"),
            started_at=row.get("started_at"),
            completed_at=row.get("completed_at"),
            failed_at=row.get("failed_at"),
            last_error=row.get("last_error", ""),
            created_at=row.get("created_at"),
            updated_at=row.get("updated_at"),
        )
