#!/usr/bin/env python3
"""
Script to create test data for cross-day fixture testing.
Removes all existing fixtures and creates 10 matches for a "yesterday fixture":
- 5 completed matches (status='done')
- 5 matches in bet status (status='bet')
"""

import sys
import os
from datetime import datetime, timedelta
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, MatchOutcomeModel, MatchTemplateModel, MatchOutcomeTemplateModel, BetModel, BetDetailModel, ExtractionStatsModel
from mbetterclient.config.settings import get_user_data_dir
from sqlalchemy.orm import joinedload

def create_basic_templates(session):
    """Create basic match templates for testing"""
    templates_data = [
        ("John Doe", "Mike Smith", "Sports Arena"),
        ("Alex Johnson", "Chris Brown", "Championship Hall"),
        ("David Wilson", "Tom Davis", "Boxing Center"),
        ("Robert Lee", "James Miller", "Fight Club"),
        ("Kevin White", "Brian Taylor", "Ring Stadium"),
        ("Steve Harris", "Paul Walker", "Combat Zone"),
        ("Mark Thompson", "Jason Clark", "Battle Ground"),
        ("Andrew Lewis", "Scott Hall", "Warrior Arena"),
        ("Peter Parker", "Bruce Wayne", "Gladiator Hall"),
        ("Tony Stark", "Clark Kent", "Champions Ring")
    ]

    for i, (fighter1, fighter2, venue) in enumerate(templates_data):
        # Create template
        template = MatchTemplateModel(
            match_number=i + 1,
            fighter1_township=fighter1,
            fighter2_township=fighter2,
            venue_kampala_township=venue,
            filename=f"template_{i+1}.txt",
            file_sha1sum=f"template_sha1_{i}",
            fixture_id=f"template_fixture_{i+1}",  # Templates need a fixture_id
            active_status=True,
            zip_filename=f"template_{i+1}.zip",
            zip_sha1sum=f"template_zip_sha1_{i}",
            zip_upload_status='completed',
            zip_validation_status='valid'
        )

        session.add(template)
        session.flush()  # Get the template ID

        # Create template outcomes
        outcomes = [
            ('WIN1', 2.10),
            ('X', 3.20),
            ('WIN2', 1.85),
            ('UNDER', 1.75),
            ('OVER', 2.05),
            ('KO1', 4.50),
            ('KO2', 6.00),
            ('PTS1', 2.80),
            ('PTS2', 3.10)
        ]

        for outcome_name, coefficient in outcomes:
            outcome = MatchOutcomeTemplateModel(
                match_id=template.id,
                column_name=outcome_name,
                float_value=coefficient
            )
            session.add(outcome)

    session.commit()

def main():
    print("🔄 Starting test fixture creation...")

    # Initialize database manager
    db_path = get_user_data_dir() / "mbetterclient.db"
    db_manager = DatabaseManager(str(db_path))
    if not db_manager.initialize():
        raise RuntimeError("Failed to initialize database")
    session = db_manager.get_session()

    try:
        print("🗑️  Removing all existing matches and bets (keeping templates)...")

        # Remove all bets and bet details first (due to foreign key constraints)
        session.query(BetDetailModel).delete()
        session.query(BetModel).delete()

        # Remove extraction stats (references matches)
        session.query(ExtractionStatsModel).delete()

        # Remove all match outcomes (due to foreign key constraints)
        session.query(MatchOutcomeModel).delete()

        # Remove all matches (but keep templates)
        session.query(MatchModel).delete()

        session.commit()
        print("✅ All existing matches and bets removed (templates preserved)")

        # Check if templates exist, create some if needed
        template_count = session.query(MatchTemplateModel).count()
        if template_count == 0:
            print("📋 No match templates found, creating basic templates...")
            create_basic_templates(session)
            template_count = session.query(MatchTemplateModel).count()
            print(f"✅ Created {template_count} basic match templates")

        # Calculate yesterday's date
        yesterday = datetime.utcnow() - timedelta(days=1)
        fixture_id = "test_yesterday_fixture"

        print(f"📅 Creating 10 matches for yesterday fixture: {fixture_id}")
        print(f"📅 Yesterday's date: {yesterday.date()}")

        # Get all available templates
        templates = session.query(MatchTemplateModel).options(joinedload(MatchTemplateModel.outcomes)).all()

        if len(templates) < 10:
            print(f"⚠️  Only {len(templates)} templates available, will reuse templates for remaining matches")

        for i in range(10):
            match_number = i + 1
            status = 'done' if i < 5 else 'bet'  # First 5 completed, next 5 in bet status

            # Select template (reuse if we run out)
            template = templates[i % len(templates)]

            # Create match from template
            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,
                status=status,
                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.timestamp()),
                result=None if status == 'bet' else 'WIN1',  # Set result for completed matches
                end_time=yesterday if status == 'done' else None,
                done=(status == 'done'),
                running=False
            )

            session.add(match)
            session.flush()  # Get the match ID

            # Copy match 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 match #{match_number}: {template.fighter1_township} vs {template.fighter2_township} - Status: {status}")

        session.commit()
        print("🎉 Test fixture creation completed!")
        print(f"📊 Created fixture '{fixture_id}' with 10 matches:")
        print("   - 5 completed matches (status='done')")
        print("   - 5 matches in bet status (status='bet')")
        print(f"   - All matches dated: {yesterday.date()}")

    except Exception as e:
        print(f"❌ Error creating test fixture: {e}")
        session.rollback()
        raise
    finally:
        session.close()

if __name__ == "__main__":
    main()