"""
UpdateCase - Update case fields in Amazon Connect Cases.
https://docs.aws.amazon.com/connect/latest/APIReference/flow-control-actions-updatecase.html
"""

from dataclasses import dataclass
from typing import Optional, Dict
import uuid
from ..base import FlowBlock
from ..serialization import to_aws_bool


@dataclass
class UpdateCase(FlowBlock):
    """
    Update case fields in Amazon Connect Cases.

    Results:
        None.

    Errors:
        - ContactNotLinked - Contact not linked after update
        - NoMatchingError - Error finding or updating the case

    Restrictions:
        None (all channels, all flow types)
    """

    link_contact_to_case: bool = False
    case_id: Optional[str] = None
    case_request_fields: Optional[Dict[str, str]] = None

    def __post_init__(self):
        self.type = "UpdateCase"
        self._build_parameters()

    def _build_parameters(self):
        """Build parameters dict from typed attributes."""
        params = {}
        params["LinkContactToCase"] = to_aws_bool(self.link_contact_to_case)
        if self.case_id is not None:
            params["CaseId"] = self.case_id
        if self.case_request_fields is not None:
            params["CaseRequestFields"] = self.case_request_fields
        self.parameters = params

    def __repr__(self) -> str:
        return f"UpdateCase(case_id='{self.case_id}')"

    def to_dict(self) -> dict:
        self._build_parameters()
        return super().to_dict()

    @classmethod
    def from_dict(cls, data: dict) -> "UpdateCase":
        params = data.get("Parameters", {})
        link = params.get("LinkContactToCase", "False")
        return cls(
            identifier=data.get("Identifier", str(uuid.uuid4())),
            link_contact_to_case=(link == "True"),
            case_id=params.get("CaseId"),
            case_request_fields=params.get("CaseRequestFields"),
            parameters=params,
            transitions=data.get("Transitions", {}),
        )
