#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
C&C Remastered Replay Parser Demo
Zeigt die komplette Funktionalität von Unit-Analyse
"""

import sys
import os
from collections import defaultdict

# Import unserer Module
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from replay_parser import ReplayEvent, parse_replay, aggregate_unit_stats
from unit_mapping import get_unit_info, get_units_by_faction


def create_realistic_demo_data():
    """Erstellt realistischere Demo-Daten für ein komplettes Match"""
    events = []
    
    # Player 1 - Allies Build
    events.extend([
        # Early Game - Infantry spam
        ReplayEvent(time=45, player_id="p1", type="UnitCreated", unit_type="rifle"),
        ReplayEvent(time=60, player_id="p1", type="UnitCreated", unit_type="rifle"),
        ReplayEvent(time=90, player_id="p1", type="UnitCreated", unit_type="rifle"),
        ReplayEvent(time=120, player_id="p1", type="UnitCreated", unit_type="rifle"),
        ReplayEvent(time=150, player_id="p1", type="UnitCreated", unit_type="engineer"),
        
        # Mid Game - Vehicles
        ReplayEvent(time=180, player_id="p1", type="UnitCreated", unit_type="light_tank"),
        ReplayEvent(time=240, player_id="p1", type="UnitCreated", unit_type="light_tank"),
        ReplayEvent(time=300, player_id="p1", type="UnitCreated", unit_type="medium_tank"),
        ReplayEvent(time=360, player_id="p1", type="UnitCreated", unit_type="medium_tank"),
        ReplayEvent(time=420, player_id="p1", type="UnitCreated", unit_type="medium_tank"),
        
        # Late Game - Air support
        ReplayEvent(time=480, player_id="p1", type="UnitCreated", unit_type="longbow"),
        ReplayEvent(time=540, player_id="p1", type="UnitCreated", unit_type="longbow"),
        
        # Economic
        ReplayEvent(time=200, player_id="p1", type="UnitCreated", unit_type="ore_truck"),
        ReplayEvent(time=400, player_id="p1", type="UnitCreated", unit_type="ore_truck"),
    ])
    
    # Player 2 - Soviet Build
    events.extend([
        # Early Game - Flamethrower rush
        ReplayEvent(time=50, player_id="p2", type="UnitCreated", unit_type="flamethrower"),
        ReplayEvent(time=70, player_id="p2", type="UnitCreated", unit_type="flamethrower"),
        ReplayEvent(time=90, player_id="p2", type="UnitCreated", unit_type="flamethrower"),
        ReplayEvent(time=110, player_id="p2", type="UnitCreated", unit_type="grenadier"),
        
        # Mid Game - Heavy armor
        ReplayEvent(time=220, player_id="p2", type="UnitCreated", unit_type="heavy_tank"),
        ReplayEvent(time=280, player_id="p2", type="UnitCreated", unit_type="heavy_tank"),
        ReplayEvent(time=340, player_id="p2", type="UnitCreated", unit_type="mammoth_tank"),
        ReplayEvent(time=400, player_id="p2", type="UnitCreated", unit_type="mammoth_tank"),
        ReplayEvent(time=460, player_id="p2", type="UnitCreated", unit_type="mammoth_tank"),
        
        # Artillery support
        ReplayEvent(time=380, player_id="p2", type="UnitCreated", unit_type="v2_rocket"),
        ReplayEvent(time=500, player_id="p2", type="UnitCreated", unit_type="v2_rocket"),
        
        # Air force
        ReplayEvent(time=440, player_id="p2", type="UnitCreated", unit_type="hind"),
        ReplayEvent(time=520, player_id="p2", type="UnitCreated", unit_type="hind"),
        
        # Economic
        ReplayEvent(time=180, player_id="p2", type="UnitCreated", unit_type="ore_truck"),
        ReplayEvent(time=350, player_id="p2", type="UnitCreated", unit_type="ore_truck"),
    ])
    
    # Combat losses
    events.extend([
        # Player 1 losses
        ReplayEvent(time=250, player_id="p1", type="UnitDestroyed", unit_type="rifle"),
        ReplayEvent(time=320, player_id="p1", type="UnitDestroyed", unit_type="rifle"),
        ReplayEvent(time=450, player_id="p1", type="UnitDestroyed", unit_type="light_tank"),
        ReplayEvent(time=580, player_id="p1", type="UnitDestroyed", unit_type="medium_tank"),
        
        # Player 2 losses
        ReplayEvent(time=270, player_id="p2", type="UnitDestroyed", unit_type="flamethrower"),
        ReplayEvent(time=330, player_id="p2", type="UnitDestroyed", unit_type="flamethrower"),
        ReplayEvent(time=410, player_id="p2", type="UnitDestroyed", unit_type="heavy_tank"),
        ReplayEvent(time=550, player_id="p2", type="UnitDestroyed", unit_type="hind"),
    ])
    
    return events


def print_detailed_stats(stats):
    """Gibt detaillierte Unit-Statistiken mit Namen aus"""
    print("=== Detaillierte Unit-Statistiken ===\n")
    
    for player_id, units in stats.items():
        player_name = f"Spieler {player_id[-1]}"  # p1 -> Spieler 1
        print(f"🎮 {player_name}:")
        
        total_built = sum(data["built"] for data in units.values())
        total_lost = sum(data["lost"] for data in units.values())
        
        print(f"   📊 Gesamt: {total_built} gebaut, {total_lost} verloren")
        print()
        
        # Gruppiert nach Kategorie
        categories = defaultdict(list)
        for unit_type, data in units.items():
            info = get_unit_info(unit_type)
            categories[info["category"]].append((unit_type, data, info))
        
        for category in ["infantry", "vehicle", "air", "naval"]:
            if category in categories:
                print(f"   📂 {category.title()}:")
                for unit_type, data, info in categories[category]:
                    if data["built"] > 0:
                        first_built = f" (erstes bei {data['first_built_second']}s)" if data["first_built_second"] else ""
                        print(f"      • {info['display_name']}: {data['built']} gebaut, {data['lost']} verloren{first_built}")
                print()


def analyze_meta(stats):
    """Analyse der Meta-Statistiken"""
    print("=== Meta-Analyse ===\n")
    
    # Fraktionsanalyse
    faction_units = defaultdict(lambda: {"built": 0, "lost": 0})
    
    for player_id, units in stats.items():
        for unit_type, data in units.items():
            info = get_unit_info(unit_type)
            if info["faction"] != "Unknown":
                faction_units[info["faction"]]["built"] += data["built"]
                faction_units[info["faction"]]["lost"] += data["lost"]
    
    print("🏛️ Fraktions-Verteilung:")
    for faction, data in faction_units.items():
        if data["built"] > 0:
            loss_rate = (data["lost"] / data["built"] * 100) if data["built"] > 0 else 0
            print(f"   • {faction}: {data['built']} gebaut, {data['lost']} verloren ({loss_rate:.1f}% Verlustrate)")
    
    print()
    
    # Beliebteste Units
    all_units = []
    for player_id, units in stats.items():
        for unit_type, data in units.items():
            if data["built"] > 0:
                info = get_unit_info(unit_type)
                all_units.append((info["display_name"], data["built"], info["faction"]))
    
    all_units.sort(key=lambda x: x[1], reverse=True)
    
    print("🔥 Top 5 meistgebaute Units:")
    for i, (name, built, faction) in enumerate(all_units[:5], 1):
        print(f"   {i}. {name} ({faction}): {built}x")


def main():
    """Demo-Hauptfunktion"""
    print("🎮 C&C Remastered Replay Parser Demo")
    print("=" * 50)
    print()
    
    # Demo-Daten erstellen
    events = create_realistic_demo_data()
    print(f"📊 Verarbeite {len(events)} Events...\n")
    
    # Statistiken aggregieren
    stats = aggregate_unit_stats(events)
    
    # Detaillierte Ausgabe
    print_detailed_stats(stats)
    
    # Meta-Analyse
    analyze_meta(stats)
    
    print("\n" + "=" * 50)
    print("✅ Demo abgeschlossen!")
    print()
    print("📝 Nächste Schritte:")
    print("   1. Echtes Replay-Binärformat implementieren")
    print("   2. Datenbank-Anbindung hinzufügen")
    print("   3. Web-UI für Statistiken entwickeln")


if __name__ == "__main__":
    main()
