# app/src/market_data/acquisition/models/status.py

from __future__ import annotations

from dataclasses import dataclass
from enum import StrEnum


# Каноническое состояние торговой доступности инструмента.
class InstrumentTradingState(StrEnum):
    OPEN = "OPEN"
    BREAK = "BREAK"
    NOT_TRADABLE = "NOT_TRADABLE"
    UNKNOWN = "UNKNOWN"


# Результат классификации сырого статуса инструмента.
@dataclass(frozen=True, slots=True)
class InstrumentStatusClassification:
    state: InstrumentTradingState
    normalized_status: str | None


_OPEN_STATUSES = frozenset(
    {
        "TRADING",
        "OPEN",
        "ACTIVE",
        "ENABLED",
        "ONLINE",
    }
)

_NOT_TRADABLE_STATUSES = frozenset(
    {
        "NOT_TRADABLE",
        "TRADING_DISABLED",
        "MARKET_DISABLED",
        "UNAVAILABLE_FOR_TRADING",
        "CLOSE_ONLY",
        "REDUCE_ONLY",
        "VIEW_ONLY",
    }
)

_BREAK_STATUSES = frozenset(
    {
        "BREAK",
        "CLOSED",
        "HALT",
        "HALTED",
        "PAUSED",
        "SUSPENDED",
        "DISABLED",
        "SETTLING",
        "POST_ONLY",
    }
)


# Классифицировать сырой статус торгового инструмента.
def classify_instrument_status(
    raw_status: str | None,
) -> InstrumentStatusClassification:
    normalized_status = str(raw_status or "").strip().upper()

    if normalized_status in _OPEN_STATUSES:
        return InstrumentStatusClassification(
            state=InstrumentTradingState.OPEN,
            normalized_status=normalized_status,
        )

    if normalized_status in _NOT_TRADABLE_STATUSES:
        return InstrumentStatusClassification(
            state=InstrumentTradingState.NOT_TRADABLE,
            normalized_status=normalized_status,
        )

    if normalized_status in _BREAK_STATUSES:
        return InstrumentStatusClassification(
            state=InstrumentTradingState.BREAK,
            normalized_status=normalized_status,
        )

    return InstrumentStatusClassification(
        state=InstrumentTradingState.UNKNOWN,
        normalized_status=normalized_status or None,
    )