from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from zempy.zosapi.analysis.enums.error_types import ErrorType
from zempy.zosapi.analysis.protocols.IMessage import IMessage

@dataclass(frozen=True, slots=True)

class Message (IMessage):
    """Python wrapper for ZOSAPI.IMessage interface."""
    code: ErrorType
    text: str

    @property
    def ok(self) -> bool:
        return self.code is ErrorType.Success

    def __bool__(self) -> bool:
        return self.ok

    @classmethod
    def from_zos(cls, msg: Any) -> "Message":
        if msg is None:
            return cls(code=ErrorType.Unknown, text="")
        text = str(getattr(msg, "Text", "") or "")
        err  = getattr(msg, "ErrorCode", None)

        if err is not None:
            name = None
            try:
                name = str(err.ToString())
            except Exception:
                try:
                    name = str(err)
                except Exception:
                    name = None
            if name:
                key = name.strip()
                try:
                    return cls(code=ErrorType[key], text=text)
                except KeyError:
                    for ec in ErrorType:
                        if ec.name.lower() == key.lower():
                            return cls(code=ec, text=text)
            try:
                val = int(err)
                for ec in ErrorType:
                    if ec.value == val:
                        return cls(code=ec, text=text)
            except Exception:
                pass
        return cls(code=ErrorType.Unknown, text=text)

    def __str__(self) -> str:
        return f"[{self.code.name}] {self.text}"