#!/usr/bin/env python3
"""
Quick start script for tutor datetime cleanup.
This script provides a simple, guided interface for running the cleanup utility.
"""

import sys
import os
from pathlib import Path

def print_banner():
    """Print the utility banner"""
    print("=" * 70)
    print("🚀 TUTOR DATETIME FIELDS CLEANUP - QUICK START")
    print("=" * 70)
    print()
    print("This utility will clean up problematic datetime fields in your database.")
    print("It's designed to fix SQLAlchemy parsing errors caused by empty strings.")
    print()

def check_dependencies():
    """Check if required dependencies are installed"""
    print("Checking dependencies...")
    
    try:
        import sqlalchemy
        print("✅ SQLAlchemy is installed")
    except ImportError:
        print("❌ SQLAlchemy is not installed")
        print("Please install it with: pip install sqlalchemy")
        return False
    
    return True

def get_cleanup_mode():
    """Get the user's preferred cleanup mode"""
    print("\nChoose your cleanup mode:")
    print("1. 🔍 SAFE MODE (Dry Run) - Show what would be changed")
    print("2. ⚡ LIVE MODE - Actually make the changes")
    print("3. ❌ Exit")
    
    while True:
        try:
            choice = input("\nEnter your choice (1-3): ").strip()
            if choice == '1':
                return True  # Dry run
            elif choice == '2':
                return False  # Live mode
            elif choice == '3':
                return None  # Exit
            else:
                print("Invalid choice. Please enter 1, 2, or 3.")
        except KeyboardInterrupt:
            print("\nExiting...")
            return None

def get_database_connection():
    """Get database connection details"""
    print("\nDatabase Connection:")
    print("Press Enter to use default (SQLite test.db), or enter custom connection")
    
    # Check for environment variables
    env_vars = []
    if os.environ.get('DATABASE_HOST'):
        env_vars.append(f"Host: {os.environ.get('DATABASE_HOST')}")
    if os.environ.get('DATABASE_NAME'):
        env_vars.append(f"Database: {os.environ.get('DATABASE_NAME')}")
    if os.environ.get('DATABASE_USER'):
        env_vars.append(f"User: {os.environ.get('DATABASE_USER')}")
    
    if env_vars:
        print("Environment variables detected:")
        for var in env_vars:
            print(f"  {var}")
        print("Press Enter to use these settings, or enter custom connection string")
    
    connection = input("Database URI (optional): ").strip()
    return connection if connection else None

def confirm_live_cleanup():
    """Get confirmation for live cleanup"""
    print("\n" + "⚠️" * 20)
    print("⚠️  WARNING: LIVE CLEANUP MODE ⚠️")
    print("⚠️" * 20)
    print()
    print("This will make PERMANENT changes to your database!")
    print("Make sure you have a backup before proceeding.")
    print()
    
    while True:
        confirm = input("Type 'YES' to confirm, or 'NO' to cancel: ").strip().upper()
        if confirm == 'YES':
            return True
        elif confirm == 'NO':
            return False
        else:
            print("Please type 'YES' or 'NO'")

def run_cleanup(dry_run, database_uri):
    """Run the actual cleanup"""
    print("\nStarting cleanup process...")
    print(f"Mode: {'🔍 DRY RUN' if dry_run else '⚡ LIVE CLEANUP'}")
    print(f"Database: {database_uri or 'Default'}")
    print()
    
    try:
        # Import and run the cleanup utility
        from cleanup_tutor_datetime_fields import TutorDatetimeCleanup
        
        cleanup = TutorDatetimeCleanup(
            database_uri=database_uri,
            dry_run=dry_run
        )
        
        success = cleanup.run_cleanup()
        
        if success:
            print("\n" + "✅" * 20)
            print("✅ CLEANUP COMPLETED SUCCESSFULLY! ✅")
            print("✅" * 20)
        else:
            print("\n" + "❌" * 20)
            print("❌ CLEANUP FAILED OR INCOMPLETE ❌")
            print("❌" * 20)
        
        return success
        
    except Exception as e:
        print(f"\n❌ Error during cleanup: {e}")
        print("Check the log file for details.")
        return False

def main():
    """Main function"""
    try:
        print_banner()
        
        # Check dependencies
        if not check_dependencies():
            print("\nPlease install the required dependencies and try again.")
            sys.exit(1)
        
        # Get cleanup mode
        dry_run = get_cleanup_mode()
        if dry_run is None:
            print("Goodbye!")
            return
        
        # Get database connection
        database_uri = get_database_connection()
        
        # Confirm live cleanup if needed
        if not dry_run:
            if not confirm_live_cleanup():
                print("Cleanup cancelled.")
                return
        
        # Run the cleanup
        success = run_cleanup(dry_run, database_uri)
        
        # Final message
        if success:
            if dry_run:
                print("\n🎯 Dry run completed! Review the results above.")
                print("To apply the changes, run this script again and choose LIVE MODE.")
            else:
                print("\n🎉 Database cleanup completed successfully!")
                print("Your database should now be free of datetime parsing errors.")
        else:
            print("\n💡 Tips for troubleshooting:")
            print("1. Check the log file for detailed error information")
            print("2. Verify your database connection and permissions")
            print("3. Try running in DRY RUN mode first")
            print("4. Ensure you have a recent database backup")
        
    except KeyboardInterrupt:
        print("\n\nOperation cancelled by user.")
    except Exception as e:
        print(f"\n❌ Unexpected error: {e}")
        print("Please check the log file for details.")

if __name__ == "__main__":
    main() 