"""
Migration script to import real Goose data from Honkingversion to Elmeg Demo
"""
import sqlite3
import sys
from datetime import datetime
from sqlmodel import Session, select
from database import engine
from models import Vertical, Venue, Tour, Show, Song, Performance

SOURCE_DB = "/Users/ten/ANTIGRAVITY/honkingversion/database.db"

def migrate_data():
    print("=" * 60)
    print("MIGRATING REAL GOOSE DATA")
    print("=" * 60)
    
    # Connect to source DB
    try:
        src_conn = sqlite3.connect(SOURCE_DB)
        src_conn.row_factory = sqlite3.Row
        src_cur = src_conn.cursor()
        print(f"✓ Connected to source: {SOURCE_DB}")
    except Exception as e:
        print(f"❌ Failed to connect to source DB: {e}")
        return

    with Session(engine) as session:
        # 1. Get or Create Goose Vertical
        vertical = session.exec(select(Vertical).where(Vertical.slug == "goose")).first()
        if not vertical:
            vertical = Vertical(name="Goose", slug="goose", description="Jam band from CT")
            session.add(vertical)
            session.commit()
            session.refresh(vertical)
            print(f"✓ Created Goose vertical (ID: {vertical.id})")
        else:
            print(f"✓ Found Goose vertical (ID: {vertical.id})")

        # 2. Clear existing data (except Users)
        print("Clearing existing show data...")
        session.exec("DELETE FROM performance")
        session.exec("DELETE FROM show")
        session.exec("DELETE FROM song")
        session.exec("DELETE FROM tour")
        session.exec("DELETE FROM venue")
        session.commit()
        print("✓ Cleared existing data")

        # 3. Migrate Venues
        print("Migrating Venues...")
        src_cur.execute("SELECT * FROM venue")
        venues = src_cur.fetchall()
        venue_map = {} # old_id -> new_id
        
        for v in venues:
            new_venue = Venue(
                name=v['name'],
                city=v['city'],
                state=v['state'],
                country=v['country']
            )
            session.add(new_venue)
            session.commit()
            session.refresh(new_venue)
            venue_map[v['id']] = new_venue.id
        print(f"✓ Migrated {len(venues)} venues")

        # 4. Migrate Tours
        print("Migrating Tours...")
        src_cur.execute("SELECT * FROM tour")
        tours = src_cur.fetchall()
        tour_map = {}
        
        for t in tours:
            # Handle date parsing if needed, assuming strings in sqlite
            start_date = datetime.strptime(t['start_date'], '%Y-%m-%d %H:%M:%S') if t['start_date'] else None
            end_date = datetime.strptime(t['end_date'], '%Y-%m-%d %H:%M:%S') if t['end_date'] else None
            
            new_tour = Tour(
                name=t['name'],
                start_date=start_date,
                end_date=end_date
            )
            session.add(new_tour)
            session.commit()
            session.refresh(new_tour)
            tour_map[t['id']] = new_tour.id
        print(f"✓ Migrated {len(tours)} tours")

        # 5. Migrate Songs
        print("Migrating Songs...")
        src_cur.execute("SELECT * FROM song")
        songs = src_cur.fetchall()
        song_map = {}
        
        for s in songs:
            new_song = Song(
                title=s['name'], # Map 'name' to 'title'
                original_artist=s['original_artist'],
                vertical_id=vertical.id
            )
            session.add(new_song)
            session.commit()
            session.refresh(new_song)
            song_map[s['id']] = new_song.id
        print(f"✓ Migrated {len(songs)} songs")

        # 6. Migrate Shows
        print("Migrating Shows...")
        src_cur.execute("SELECT * FROM show")
        shows = src_cur.fetchall()
        show_map = {}
        
        for s in shows:
            show_date = datetime.strptime(s['date'], '%Y-%m-%d %H:%M:%S') if s['date'] else None
            
            new_show = Show(
                date=show_date,
                vertical_id=vertical.id,
                venue_id=venue_map.get(s['venue_id']),
                tour_id=tour_map.get(s['tour_id']),
                notes=s['notes']
            )
            session.add(new_show)
            session.commit()
            session.refresh(new_show)
            show_map[s['id']] = new_show.id
        print(f"✓ Migrated {len(shows)} shows")

        # 7. Migrate Performances
        print("Migrating Performances...")
        src_cur.execute("SELECT * FROM songperformance")
        perfs = src_cur.fetchall()
        
        for p in perfs:
            # Skip if show or song missing (data integrity)
            if p['show_id'] not in show_map or p['song_id'] not in song_map:
                continue
                
            new_perf = Performance(
                show_id=show_map[p['show_id']],
                song_id=song_map[p['song_id']],
                position=p['position'],
                set_name=p['set_name'],
                segue=bool(p['segue']),
                notes=p['notes']
            )
            session.add(new_perf)
        session.commit()
        print(f"✓ Migrated {len(perfs)} performances")

    src_conn.close()
    print("=" * 60)
    print("✓ MIGRATION COMPLETE")
    print("=" * 60)

if __name__ == "__main__":
    migrate_data()
