"""
Job status service.

Single Responsibility: Query job status and history.
"""

from typing import Optional

from ..clients.dynamodb_client import DynamoDBClient


class JobStatusService:
    """
    Handle job status queries.

    Simple wrapper around DynamoDB client for status operations.
    Max 3 methods per CLAUDE.md guidelines.
    """

    def __init__(self, dynamodb_client: DynamoDBClient):
        """
        Initialize job status service.

        Args:
            dynamodb_client: DynamoDB client for state queries
        """
        self.dynamodb_client = dynamodb_client

    def get_job_status(self, job_id: str) -> Optional[dict]:
        """
        Get current job status.

        Args:
            job_id: Job identifier

        Returns:
            Job record dict or None if not found

        Raises:
            RuntimeError: If query fails
        """
        job = self.dynamodb_client.get_job(job_id)

        if job is None:
            return None

        # Return simplified status view
        return {
            "job_id": job["job_id"],
            "job_type": job["job_type"],
            "dataset_name": job["dataset_name"],
            "status": job["status"],
            "created_at": job["created_at"],
            "started_at": job.get("started_at"),
            "completed_at": job.get("completed_at"),
            "result": job.get("result"),
            "error": job.get("error"),
        }

    def get_user_jobs(
        self, user_id: str, limit: int = 10
    ) -> list[dict]:
        """
        Get recent jobs for a user.

        Args:
            user_id: User identifier
            limit: Maximum number of jobs to return

        Returns:
            List of job status dicts

        Raises:
            RuntimeError: If query fails
        """
        jobs = self.dynamodb_client.query_jobs_by_user(user_id, limit)

        # Return simplified status view for each job
        return [
            {
                "job_id": job["job_id"],
                "job_type": job["job_type"],
                "dataset_name": job["dataset_name"],
                "status": job["status"],
                "created_at": job["created_at"],
                "completed_at": job.get("completed_at"),
            }
            for job in jobs
        ]

    def is_job_complete(self, job_id: str) -> tuple[bool, Optional[str]]:
        """
        Check if job is complete (success or failure).

        Args:
            job_id: Job identifier

        Returns:
            Tuple of (is_complete, final_status)
            final_status is 'completed', 'failed', or None

        Raises:
            RuntimeError: If query fails
        """
        job = self.dynamodb_client.get_job(job_id)

        if job is None:
            return False, None

        status = job["status"]
        if status in ["completed", "failed"]:
            return True, status

        return False, None
