#!/usr/bin/env python
"""
Run migrations skipping reports app
Runs migrations for all apps except reports which has issues
"""

import os
import sys
import django
from django.core.management import execute_from_command_line

def setup_django():
    """Setup Django environment"""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
    django.setup()

def run_migrations_skip_reports():
    """Run migrations for all apps except reports"""
    print("=== RUNNING MIGRATIONS (SKIPPING REPORTS) ===")
    
    try:
        # Run makemigrations for specific apps
        apps_to_migrate = ['users', 'loans', 'utils', 'admin', 'auth', 'contenttypes', 'sessions']
        
        for app in apps_to_migrate:
            print(f"  Running makemigrations for {app} app...")
            try:
                execute_from_command_line(['manage.py', 'makemigrations', app, '--noinput'])
                print(f"    ✓ {app} migrations completed")
            except Exception as e:
                print(f"    ⚠ {app} migrations failed: {e}")
        
        # Skip reports app
        print("  Skipping reports app (has migration issues)")
        
        # Run migrate for all apps
        print("  Running migrate...")
        execute_from_command_line(['manage.py', 'migrate', '--noinput'])
        print("    ✓ migrate completed")
        
        return True
        
    except Exception as e:
        print(f"    ✗ Migration failed: {e}")
        return False

def main():
    """Main function"""
    print("=== MIGRATION RUNNER (SKIP REPORTS) ===")
    print("Running migrations for all apps except reports.\n")
    
    try:
        setup_django()
        
        # Run migrations
        if run_migrations_skip_reports():
            print("\n=== MIGRATIONS COMPLETE ===")
            print("✓ All migrations have been applied successfully!")
            print("✓ Database is up to date")
            print("⚠ Reports app migrations were skipped")
            print("\n🎉 Your application is ready!")
            print("\n📋 Next steps:")
            print("1. Test your application: python manage.py runserver")
            print("2. Check the portfolio assignment page")
            print("3. Test the enhanced rollover functionality")
            return True
        else:
            print("\n=== MIGRATIONS FAILED ===")
            print("⚠ Migration issues occurred")
            return False
        
    except Exception as e:
        print(f"\n❌ Migration failed: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
