#!/usr/bin/env python3
"""
Test script to create a yesterday fixture with 5 completed matches and 5 bet matches
for testing cross-day fixture handling.
"""

import sys
import os
from datetime import datetime, timedelta
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

# Add the project root to the Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from mbetterclient.database.manager import DatabaseManager
from mbetterclient.database.models import MatchModel, MatchOutcomeModel, MatchTemplateModel, MatchOutcomeTemplateModel
from mbetterclient.config.settings import get_user_data_dir

def create_yesterday_fixture():
    """Create a fixture from yesterday with 5 completed and 5 bet 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 manager")
        return False

    Session = sessionmaker(bind=db_manager.engine)
    session = Session()

    try:
        # Get yesterday's date
        yesterday = datetime.utcnow() - timedelta(days=1)
        yesterday_start = datetime.combine(yesterday.date(), datetime.min.time())

        # Generate unique fixture ID
        import uuid
        fixture_id = f"yesterday_test_{uuid.uuid4().hex[:8]}"

        print(f"Creating yesterday fixture: {fixture_id}")

        # Get some match templates to use as base
        templates = session.query(MatchTemplateModel).filter(
            MatchTemplateModel.active_status == True
        ).limit(10).all()

        if len(templates) < 10:
            print(f"Warning: Only {len(templates)} templates available, need 10")
            if len(templates) < 5:
                print("Error: Need at least 5 templates")
                return False

        match_number = 1

        # Create 5 completed matches
        print("Creating 5 completed matches...")
        for i in range(5):
            template = templates[i % len(templates)]

            # Create completed match
            match = MatchModel(
                match_number=match_number,
                fighter1_township=template.fighter1_township,
                fighter2_township=template.fighter2_township,
                venue_kampala_township=template.venue_kampala_township,
                start_time=yesterday_start + timedelta(hours=i),  # Spread throughout yesterday
                status='done',
                fixture_id=fixture_id,
                filename=template.filename,
                file_sha1sum=template.file_sha1sum,
                active_status=True,
                zip_filename=template.zip_filename,
                zip_sha1sum=template.zip_sha1sum,
                zip_upload_status='completed',
                zip_validation_status='valid',
                fixture_active_time=int(yesterday_start.timestamp()),
                result='WIN1',  # Simple result
                end_time=yesterday_start + timedelta(hours=i, minutes=30),
                done=True,
                running=False
            )

            session.add(match)
            session.flush()

            # Copy outcomes from template
            for template_outcome in template.outcomes:
                outcome = MatchOutcomeModel(
                    match_id=match.id,
                    column_name=template_outcome.column_name,
                    float_value=template_outcome.float_value
                )
                session.add(outcome)

            print(f"  Created completed match #{match_number}: {match.fighter1_township} vs {match.fighter2_township}")
            match_number += 1

        # Create 5 bet matches
        print("Creating 5 bet matches...")
        for i in range(5, 10):
            template = templates[i % len(templates)]

            # Create bet match
            match = MatchModel(
                match_number=match_number,
                fighter1_township=template.fighter1_township,
                fighter2_township=template.fighter2_township,
                venue_kampala_township=template.venue_kampala_township,
                start_time=yesterday_start + timedelta(hours=i),  # Continue from yesterday
                status='bet',
                fixture_id=fixture_id,
                filename=template.filename,
                file_sha1sum=template.file_sha1sum,
                active_status=True,
                zip_filename=template.zip_filename,
                zip_sha1sum=template.zip_sha1sum,
                zip_upload_status='completed',
                zip_validation_status='valid',
                fixture_active_time=int(yesterday_start.timestamp()),
                result=None,  # No result yet
                end_time=None,
                done=False,
                running=False
            )

            session.add(match)
            session.flush()

            # Copy outcomes from template
            for template_outcome in template.outcomes:
                outcome = MatchOutcomeModel(
                    match_id=match.id,
                    column_name=template_outcome.column_name,
                    float_value=template_outcome.float_value
                )
                session.add(outcome)

            print(f"  Created bet match #{match_number}: {match.fighter1_township} vs {match.fighter2_township}")
            match_number += 1

        session.commit()
        print(f"\nSuccessfully created yesterday fixture '{fixture_id}' with:")
        print("  - 5 completed matches")
        print("  - 5 bet matches")
        print("  - All matches from yesterday")
        print("\nTo test: Start the game without providing a fixture_id.")
        print("The system should create a new fixture for today and play the remaining 5 bet matches from yesterday first.")

        return True

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

if __name__ == "__main__":
    print("Creating test fixture with yesterday's matches...")
    success = create_yesterday_fixture()
    if success:
        print("\nTest fixture created successfully!")
    else:
        print("\nFailed to create test fixture!")
        sys.exit(1)