"""Shared ActionTracker status helpers for deployment flows."""

from __future__ import annotations

from contextlib import suppress
from dataclasses import dataclass
from typing import Any


def safe_update_status(action_tracker: Any, step_code: str, status: str, description: str) -> None:
    """Best-effort status update that never raises to caller."""
    with suppress(Exception):
        if hasattr(action_tracker, "update_status"):
            action_tracker.update_status(step_code, status, description)


def safe_log_error(action_tracker: Any, file_path: str, location: str, message: str) -> None:
    """Best-effort tracker error logging."""
    with suppress(Exception):
        if hasattr(action_tracker, "log_error"):
            action_tracker.log_error(file_path, location, message)


@dataclass(frozen=True)
class DeployStatusCodes:
    """Canonical deployment status step codes."""

    ACK: str = "MDL_DPY_ACK"
    MODEL_READY: str = "MDL_DPY_MDL"
    STARTED: str = "MDL_DPY_STR"
    ERROR: str = "MDL_DPY_ERR"


class DeployStatusReporter:
    """Semantic status reporter for deploy lifecycle transitions."""

    def __init__(self, action_tracker: Any, codes: DeployStatusCodes | None = None) -> None:
        """Create a reporter backed by an ActionTracker-like object."""
        self.action_tracker = action_tracker
        self.codes = codes or DeployStatusCodes()

    def acknowledged(self, msg: str = "Model Deployment has been acknowledged") -> None:
        """Emit deployment-acknowledged status."""
        safe_update_status(self.action_tracker, self.codes.ACK, "OK", msg)

    def model_ready(self, msg: str = "Model loaded for deployment") -> None:
        """Emit model-ready status after loading succeeds."""
        safe_update_status(self.action_tracker, self.codes.MODEL_READY, "OK", msg)

    def started(self, msg: str = "Model deployment started") -> None:
        """Emit deployment-started status after server boot."""
        safe_update_status(self.action_tracker, self.codes.STARTED, "OK", msg)

    def failed(self, msg: str) -> None:
        """Emit deployment-failed status with error context."""
        safe_update_status(self.action_tracker, self.codes.ERROR, "ERROR", msg)
