#!/usr/bin/env python3
"""
Fix Tour Dates Script
Iterates through all Tours, finds their associated shows, and updates
the tour's start_date and end_date based on the range of show dates.
"""
from sqlmodel import Session, select
from database import engine
from models import Tour, Show
from datetime import datetime

def fix_tour_dates():
    print("="*60)
    print("FIX TOUR DATES")
    print("="*60)
    
    with Session(engine) as session:
        tours = session.exec(select(Tour)).all()
        print(f"Found {len(tours)} tours to process.")
        
        updated_count = 0
        
        for tour in tours:
            # Get all shows for this tour
            shows = session.exec(
                select(Show).where(Show.tour_id == tour.id)
            ).all()
            
            if not shows:
                print(f"Skipping '{tour.name}' - No shows found.")
                continue
                
            dates = [s.date for s in shows]
            min_date = min(dates)
            max_date = max(dates)
            
            # Check if update is needed
            needs_update = False
            if tour.start_date != min_date:
                tour.start_date = min_date
                needs_update = True
            
            if tour.end_date != max_date:
                tour.end_date = max_date
                needs_update = True
                
            if needs_update:
                session.add(tour)
                updated_count += 1
                print(f"Updated '{tour.name}': {min_date.date()} - {max_date.date()}")
        
        session.commit()
        print(f"\nSuccessfully updated {updated_count} tours.")

if __name__ == "__main__":
    fix_tour_dates()
