import logging
from typing import Any, Dict, List, Optional

logger = logging.getLogger(__name__)

def safe_join(val):
    """Verbindet Listen-Elemente zu einem String oder gibt den Wert direkt zurück."""
    if isinstance(val, list):
        # Filtert leere Einträge heraus und verbindet den Rest mit Komma
        clean_list = [str(i).strip() for i in val if str(i).strip()]
        return ", ".join(clean_list) if clean_list else ""
    return str(val) if val is not None else ""

def generate_statistics(df_tn: List[Dict[str, Any]], df_gf: List[Dict[str, Any]], event_info: Dict[str, Any]) -> Dict[str, Any]:
    """
    Generates structured statistics data for the event dashboard.
    Returns a dictionary suitable for JSON response.
    """
    total_tn = len(df_tn)
    
    # Identify leaders within the participant list
    # Leaders are those who are in df_tn and have a name match in df_gf
    leader_names = {(l["name.first_name"], l["name.last_name"]) for l in df_gf}
    total_gf = 0
    for tn in df_tn:
        if (tn.get("name.first_name"), tn.get("name.last_name")) in leader_names:
            total_gf += 1

    # Stamm distribution
    stamm_counts = {}
    # Search for 'stamm' in cleaned column names
    stamm_col = next((k for k in df_tn[0].keys() if "stamm" in k.lower()), None) if df_tn else None
    
    for tn in df_tn:
        stamm = tn.get(stamm_col) if stamm_col else None
        if isinstance(stamm, list) and stamm:
            stamm = stamm[0]
        if stamm:
            stamm_counts[stamm] = stamm_counts.get(stamm, 0) + 1

    # Diet stats
    diet_counts = {"Meat": 0, "Vegetarian": 0, "Vegan": 0, "Other": 0}
    # Find diet column - it might be renamed or still col_id
    diet_col = next((k for k in df_tn[0].keys() if "diet" in k.lower() or "ernaehrung" in k.lower() or "ernährung" in k.lower()), None) if df_tn else None
    
    for tn in df_tn:
        diet = tn.get(diet_col) if diet_col else None
        if isinstance(diet, list) and diet:
            diet = diet[0]
        
        diet_str = str(diet).strip().capitalize() if diet else "Nicht angegeben"
        if diet_str in diet_counts:
            diet_counts[diet_str] += 1
        elif diet_str != "Nicht angegeben":
            diet_counts["Other"] += 1

    # Ticket stats
    ticket_counts = {}
    ticket_col = next((k for k in df_tn[0].keys() if "ticket" in k.lower() or "oepnv" in k.lower()), None) if df_tn else None
    for tn in df_tn:
        ticket = tn.get(ticket_col) if ticket_col else None
        if isinstance(ticket, list) and ticket:
            ticket = ticket[0]
        if ticket:
            ticket_counts[ticket] = ticket_counts.get(ticket, 0) + 1

    # Age bins for public transport (Bahntickets)
    age_bins = {"< 15": 0, "15-26": 0, "27+": 0}
    for tn in df_tn:
        age = tn.get("age_at_event")
        if age is not None:
            if age < 15:
                age_bins["< 15"] += 1
            elif 15 <= age <= 26:
                age_bins["15-26"] += 1
            else:
                age_bins["27+"] += 1

    # Allergies and intolerances
    allergies_list = []
    intox_col = next((k for k in df_tn[0].keys() if "intolerance" in k.lower() or "unverträglichkeit" in k.lower()), None) if df_tn else None
    for tn in df_tn:
        intox = tn.get(intox_col)
        if isinstance(intox, list):
            intox = ", ".join([str(i).strip() for i in intox if str(i).strip()])
        
        if intox and str(intox).strip():
            first = tn.get("name.first_name", "")
            last = tn.get("name.last_name", "")
            last_initial = f"{last[0]}." if last else ""
            allergies_list.append({
                "name": f"{first} {last_initial}".strip(),
                "note": safe_join(intox)
            })

    # Health notes
    health_list = []
    health_col = next((k for k in df_tn[0].keys() if "health" in k.lower() or "gesundheit" in k.lower()), None) if df_tn else None
    for tn in df_tn:
        health = tn.get(health_col)
        if health and str(health).strip():
            first = tn.get("name.first_name", "")
            last = tn.get("name.last_name", "")
            last_initial = f"{last[0]}." if last else ""
            health_list.append({
                "name": f"{first} {last_initial}".strip(),
                "note": safe_join(health)
            })

    return {
        "event_title": event_info.get("title", "Event"),
        "total_participants": total_tn,
        "total_leaders": total_gf,
        "stamm_distribution": stamm_counts,
        "diet_stats": diet_counts,
        "ticket_stats": ticket_counts,
        "age_distribution": age_bins,
        "allergies": allergies_list,
        "health_notes": health_list,
        "has_ticket_data": ticket_col is not None
    }
