"""
Data models for the DeltaCAT REST client.

Lightweight dataclasses with no external dependencies beyond stdlib.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional


@dataclass
class ClaimedJob:
    """A job claimed by this worker via GET /v1/jobs/next."""

    job_id: str = ""
    subscriber_id: str = ""
    worker_id: str = ""
    claimed_at: Optional[str] = None
    heartbeat_timeout_seconds: int = 120
    data_access: Dict[str, Any] = field(default_factory=dict)
    target_upload: Dict[str, Any] = field(default_factory=dict)
    credentials: Optional[Dict[str, Any]] = None
    context: Dict[str, Any] = field(default_factory=dict)

    @classmethod
    def from_response(cls, data: Dict[str, Any]) -> "ClaimedJob":
        ctx = data.get("context", {})
        return cls(
            job_id=data.get("job_id", ""),
            subscriber_id=data.get("subscriber_id", ""),
            worker_id=data.get("worker_id", ""),
            claimed_at=data.get("claimed_at"),
            heartbeat_timeout_seconds=data.get("heartbeat_timeout_seconds", 120),
            data_access=ctx.get("data_access", {}),
            target_upload=ctx.get("target_upload", {}),
            credentials=ctx.get("credentials"),
            context=ctx,
        )

    def get_source_files(self, table_ref: str) -> List[Dict[str, Any]]:
        plan = self.data_access.get(table_ref, {})
        return plan.get("files", [])

    def get_staging_dir(self, table_ref: str) -> Optional[str]:
        upload = self.target_upload.get(table_ref, {})
        return upload.get("staging_dir")

    def get_credentials(self, endpoint_url: str = "default") -> Optional[Dict[str, str]]:
        if self.credentials is None:
            return None
        return self.credentials.get(endpoint_url)


@dataclass
class JobStatus:
    """Status of a dispatched job."""

    job_id: str = ""
    state: str = "pending"
    progress: float = 0.0
    progress_message: str = ""
    worker_id: Optional[str] = None
    error: Optional[str] = None
    result: Dict[str, Any] = field(default_factory=dict)

    @classmethod
    def from_response(cls, data: Dict[str, Any]) -> "JobStatus":
        return cls(
            job_id=data.get("job_id", ""),
            state=data.get("state", "pending"),
            progress=data.get("progress", 0.0),
            progress_message=data.get("progress_message", ""),
            worker_id=data.get("worker_id"),
            error=data.get("error"),
            result=data.get("result", {}),
        )
