#!/usr/bin/env python3
"""
Script to create test matches for the cashier interface
"""

import sys
from pathlib import Path
from datetime import datetime, date, timedelta

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

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

def create_test_matches():
    """Create some test matches for the cashier interface"""

    # Use the default database path
    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 False

    session = db_manager.get_session()
    try:
        # Check if matches already exist
        existing_count = session.query(MatchModel).count()
        if existing_count > 0:
            print(f"Database already has {existing_count} matches. Skipping creation.")
            return True

        # Create test matches for today
        today = date.today()
        now = datetime.now()

        # Create matches for fixture 1 (today's matches)
        fixture_1_matches = [
            MatchModel(
                fixture_id=1,
                match_number=1,
                fighter1_township="Kampala Central",
                fighter2_township="Nakawa",
                venue_kampala_township="Main Arena",
                start_time=datetime.combine(today, datetime.min.time()) + timedelta(hours=10),
                status="pending",
                created_at=now - timedelta(days=1)
            ),
            MatchModel(
                fixture_id=1,
                match_number=2,
                fighter1_township="Makindye",
                fighter2_township="Rubaga",
                venue_kampala_township="Main Arena",
                start_time=datetime.combine(today, datetime.min.time()) + timedelta(hours=11),
                status="pending",
                created_at=now - timedelta(days=1)
            ),
            MatchModel(
                fixture_id=1,
                match_number=3,
                fighter1_township="Kawempe",
                fighter2_township="Wandegeya",
                venue_kampala_township="Secondary Arena",
                start_time=datetime.combine(today, datetime.min.time()) + timedelta(hours=14),
                status="pending",
                created_at=now - timedelta(days=1)
            ),
            MatchModel(
                fixture_id=1,
                match_number=4,
                fighter1_township="Ntinda",
                fighter2_township="Kololo",
                venue_kampala_township="Main Arena",
                start_time=datetime.combine(today, datetime.min.time()) + timedelta(hours=15),
                status="pending",
                created_at=now - timedelta(days=1)
            ),
            MatchModel(
                fixture_id=1,
                match_number=5,
                fighter1_township="Lubaga",
                fighter2_township="Mengo",
                venue_kampala_township="Secondary Arena",
                start_time=datetime.combine(today, datetime.min.time()) + timedelta(hours=16),
                status="pending",
                created_at=now - timedelta(days=1)
            )
        ]

        # Create matches for fixture 2 (tomorrow's matches)
        tomorrow = today + timedelta(days=1)
        fixture_2_matches = [
            MatchModel(
                fixture_id=2,
                match_number=1,
                fighter1_township="Entebbe",
                fighter2_township="Mukono",
                venue_kampala_township="Main Arena",
                start_time=datetime.combine(tomorrow, datetime.min.time()) + timedelta(hours=10),
                status="scheduled",
                created_at=now - timedelta(days=1)
            ),
            MatchModel(
                fixture_id=2,
                match_number=2,
                fighter1_township="Jinja",
                fighter2_township="Iganga",
                venue_kampala_township="Secondary Arena",
                start_time=datetime.combine(tomorrow, datetime.min.time()) + timedelta(hours=11),
                status="scheduled",
                created_at=now - timedelta(days=1)
            )
        ]

        # Add all matches to the session
        all_matches = fixture_1_matches + fixture_2_matches
        for match in all_matches:
            session.add(match)

        # Commit the changes
        session.commit()

        print(f"Successfully created {len(all_matches)} test matches:")
        print(f"  - Fixture 1: {len(fixture_1_matches)} matches (today)")
        print(f"  - Fixture 2: {len(fixture_2_matches)} matches (tomorrow)")

        # Verify the matches were created
        total_count = session.query(MatchModel).count()
        print(f"Total matches in database: {total_count}")

        return True

    except Exception as e:
        print(f"Error creating test matches: {e}")
        session.rollback()
        return False
    finally:
        session.close()
        db_manager.close()

if __name__ == "__main__":
    print("Creating test matches for cashier interface...")
    success = create_test_matches()
    if success:
        print("\n✅ Test matches created successfully!")
        print("The cashier interface should now display pending matches.")
    else:
        print("\n❌ Failed to create test matches.")
        sys.exit(1)