#!/usr/bin/env python3
"""
Script to check the current state of matches in the database
"""

import sys
from pathlib import Path

# Add the project root to Python path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from mbetterclient.database.manager import DatabaseManager
from mbetterclient.database.models import MatchModel
from mbetterclient.config.settings import get_user_data_dir

def main():
    print("🔍 Checking database matches...")

    # Initialize database manager
    db_path = get_user_data_dir() / "mbetterclient.db"
    db_manager = DatabaseManager(str(db_path))
    if not db_manager.initialize():
        print("❌ Failed to initialize database")
        return

    session = db_manager.get_session()

    try:
        # Get all matches
        matches = session.query(MatchModel).filter(MatchModel.active_status == True).all()

        print(f"📊 Found {len(matches)} active matches in database")

        if not matches:
            print("❌ No active matches found")
            return

        # Group by fixture
        fixtures = {}
        for match in matches:
            if match.fixture_id not in fixtures:
                fixtures[match.fixture_id] = []
            fixtures[match.fixture_id].append(match)

        for fixture_id, fixture_matches in fixtures.items():
            print(f"\n🏟️  Fixture: {fixture_id}")
            print(f"   Total matches: {len(fixture_matches)}")

            # Count by status
            status_counts = {}
            for match in fixture_matches:
                status = match.status
                if status not in status_counts:
                    status_counts[status] = 0
                status_counts[status] += 1

            print(f"   Status counts: {status_counts}")

            # Show details for first few matches
            print("   First 5 matches:")
            for i, match in enumerate(fixture_matches[:5]):
                print(f"     #{match.match_number}: {match.fighter1_township} vs {match.fighter2_township} - Status: {match.status} - Start: {match.start_time}")

            if len(fixture_matches) > 5:
                print(f"     ... and {len(fixture_matches) - 5} more matches")

            # Check if fixture is from yesterday
            if fixture_matches and fixture_matches[0].start_time:
                from datetime import datetime, timedelta
                yesterday = datetime.utcnow() - timedelta(days=1)
                match_date = fixture_matches[0].start_time.date()
                yesterday_date = yesterday.date()
                is_yesterday = match_date == yesterday_date
                print(f"   Date: {match_date} - Is yesterday: {is_yesterday}")

    except Exception as e:
        print(f"❌ Error checking database: {e}")
        import traceback
        traceback.print_exc()
    finally:
        session.close()

if __name__ == "__main__":
    main()