#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import json
import codecs
from datetime import datetime

# UTF-8 encoding for Windows console
if sys.platform == "win32":
    sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
    sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')

def count_all_sessions():
    """Zählt alle Sessions getrennt nach Kategorien"""
    
    chat_index_path = "chat-logs/chat-index.json"
    
    if not os.path.exists(chat_index_path):
        print("❌ chat-index.json nicht gefunden!")
        return
    
    with open(chat_index_path, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    chats = data.get('chats', [])
    
    # Kategorisiere Sessions
    categories = {}
    total_sessions = len(chats)
    total_messages = 0
    
    for chat in chats:
        category = chat.get('category', 'unknown')
        messages = chat.get('messages', 0)
        date = chat.get('date', '')
        
        if category not in categories:
            categories[category] = {
                'sessions': [],
                'total_messages': 0,
                'count': 0
            }
        
        categories[category]['sessions'].append({
            'date': date,
            'messages': messages,
            'title': chat.get('title', ''),
            'participants': len(chat.get('participants', []))
        })
        categories[category]['total_messages'] += messages
        categories[category]['count'] += 1
        total_messages += messages
    
    print("=== MINECRAFT CHAT WEBSITE - VOLLSTÄNDIGE ÜBERSICHT ===")
    print(f"Total Sessions: {total_sessions}")
    print(f"Total Messages: {total_messages:,}")
    print("=" * 60)
    
    # Kategorie-Details
    for category, info in sorted(categories.items()):
        if category == 'crea-1':
            print(f"\n🏰 CREATIVE MODE ({info['count']} Sessions)")
            print(f"   📊 Total Messages: {info['total_messages']:,}")
        elif category == 'survival-1':
            print(f"\n⛏️ SURVIVAL MODE ({info['count']} Sessions)")
            print(f"   📊 Total Messages: {info['total_messages']:,}")
        elif category == 'event':
            print(f"\n🎉 THESUR EVENT ({info['count']} Sessions)")
            print(f"   📊 Total Messages: {info['total_messages']:,}")
        elif category == 'test':
            print(f"\n🔧 TESTING ({info['count']} Sessions)")
            print(f"   📊 Total Messages: {info['total_messages']:,}")
        else:
            print(f"\n❓ {category.upper()} ({info['count']} Sessions)")
            print(f"   📊 Total Messages: {info['total_messages']:,}")
        
        # Sortiere Sessions nach Datum
        sessions = sorted(info['sessions'], key=lambda x: x['date'])
        
        # Zeige Sessions
        for session in sessions:
            date_obj = datetime.strptime(session['date'], '%Y-%m-%d')
            date_formatted = date_obj.strftime('%B %d, %Y')
            print(f"   📅 {session['date']}: {session['messages']:,} messages, {session['participants']} players")
        
        if category == 'event':
            # Spezielle THESUR Statistiken
            dates = [s['date'] for s in sessions]
            if dates:
                print(f"   📊 Date range: {min(dates)} to {max(dates)}")
                print(f"   📊 Timespan: {len(set(dates))} different days")
    
    print("\n" + "=" * 60)
    print("🎯 ZUSAMMENFASSUNG:")
    for category, info in sorted(categories.items()):
        icon = {'crea-1': '🏰', 'survival-1': '⛏️', 'event': '🎉', 'test': '🔧'}.get(category, '❓')
        print(f"   {icon} {category}: {info['count']} sessions, {info['total_messages']:,} messages")

if __name__ == "__main__":
    count_all_sessions()
