from dataclasses import dataclass
from collections import defaultdict
from typing import List, Dict, Any


@dataclass
class ReplayEvent:
    """Represents a single event from a C&C Remastered replay"""
    time: int          # Sekunden seit Spielstart
    player_id: str
    type: str          # "UnitCreated", "UnitDestroyed"
    unit_type: str     # "medium_tank", "rifle", ...


def parse_replay(file_path: str) -> List[ReplayEvent]:
    """
    Liest Replay-Datei und gibt eine Liste von ReplayEvents zurück.
    (Binary-Parsing kommt im nächsten Schritt)
    """
    events = []

    # TODO: Binary parsing
    # Platzhalter für jetzt:
    events.append(ReplayEvent(
        time=120,
        player_id="p1",
        type="UnitCreated",
        unit_type="medium_tank"
    ))

    events.append(ReplayEvent(
        time=300,
        player_id="p1",
        type="UnitCreated",
        unit_type="medium_tank"
    ))

    events.append(ReplayEvent(
        time=450,
        player_id="p1",
        type="UnitDestroyed",
        unit_type="medium_tank"
    ))

    events.append(ReplayEvent(
        time=180,
        player_id="p1",
        type="UnitCreated",
        unit_type="rifle"
    ))

    events.append(ReplayEvent(
        time=240,
        player_id="p1",
        type="UnitCreated",
        unit_type="rifle"
    ))

    events.append(ReplayEvent(
        time=360,
        player_id="p2",
        type="UnitCreated",
        unit_type="heavy_tank"
    ))

    return events


def aggregate_unit_stats(events: List[ReplayEvent]) -> Dict[str, Dict[str, Dict[str, Any]]]:
    """
    Aggregiert Unit-Statistiken aus Replay-Events
    
    Returns:
        {
            "player_id": {
                "unit_type": {
                    "built": int,
                    "lost": int,
                    "first_built_second": int or None
                }
            }
        }
    """
    stats = defaultdict(lambda: defaultdict(lambda: {
        "built": 0,
        "lost": 0,
        "first_built_second": None
    }))

    for e in events:
        unit = stats[e.player_id][e.unit_type]

        if e.type == "UnitCreated":
            unit["built"] += 1
            if unit["first_built_second"] is None:
                unit["first_built_second"] = e.time

        elif e.type == "UnitDestroyed":
            unit["lost"] += 1

    return dict(stats)


def print_unit_stats(stats: Dict[str, Dict[str, Dict[str, Any]]]):
    """Gibt Unit-Statistiken lesbar aus"""
    print("=== Unit Statistiken ===")
    
    for player_id, units in stats.items():
        print(f"\nSpieler {player_id}:")
        
        for unit_type, data in units.items():
            print(f"  {unit_type}:")
            print(f"    Gebaut: {data['built']}")
            print(f"    Verloren: {data['lost']}")
            print(f"    Erstes mal gebaut: {data['first_built_second']}s")


if __name__ == "__main__":
    # Test mit Platzhalter-Daten
    events = parse_replay("dummy.replay")
    stats = aggregate_unit_stats(events)
    print_unit_stats(stats)
