from __future__ import annotations

from dataclasses import dataclass
from datetime import date
from xml.etree import ElementTree as ET


@dataclass(slots=True)
class ParsedTournament:
    external_id: str
    level: str
    name_ru: str
    name_en: str
    common_name_ru: str
    common_name_en: str
    season_part: str
    season: str
    start_date: date | None
    end_date: date | None
    round_code: str
    game_id_supported: bool
    raw_xml: str


def parse_date(value: str | None) -> date | None:
    value = str(value or "").strip()
    if not value or value == "0000-00-00":
        return None
    try:
        return date.fromisoformat(value)
    except ValueError:
        return None


def parse_tournaments_xml(content: bytes | str) -> list[ParsedTournament]:
    raw = content.encode("utf-8") if isinstance(content, str) else content
    root = ET.fromstring(raw)
    result: list[ParsedTournament] = []
    for node in root.findall(".//Tournament"):
        attrs = node.attrib
        external_id = str(attrs.get("id") or "").strip()
        if not external_id:
            continue
        result.append(
            ParsedTournament(
                external_id=external_id,
                level=str(attrs.get("level") or "").strip().lower(),
                name_ru=str(attrs.get("name") or "").strip(),
                name_en=str(attrs.get("nameEn") or "").strip(),
                common_name_ru=str(attrs.get("nameCommon") or "").strip(),
                common_name_en=str(attrs.get("nameCommonEn") or "").strip(),
                season_part=str(attrs.get("seasonPart") or "").strip().lower(),
                season=str(attrs.get("season") or "").strip(),
                start_date=parse_date(attrs.get("startDate")),
                end_date=parse_date(attrs.get("endDate")),
                round_code=str(attrs.get("round") or "").strip().lower(),
                game_id_supported=str(attrs.get("gameid") or "").lower()
                in {"true", "1", "yes"},
                raw_xml=ET.tostring(node, encoding="unicode"),
            )
        )
    return result
