"""Migration script to transition from monolithic app.py to modular command structure."""

import os
import shutil
from datetime import datetime


def migrate_cli():
    """Migrate from old app.py to new modular structure."""
    cli_dir = os.path.dirname(os.path.abspath(__file__))
    old_app = os.path.join(cli_dir, "app.py")
    new_app = os.path.join(cli_dir, "app_new.py")
    backup_app = os.path.join(cli_dir, f"app_old_{datetime.now().strftime('%Y%m%d_%H%M%S')}.py")

    print("Flow CLI Migration")
    print("==================")
    print(f"Old app.py: {os.path.getsize(old_app):,} bytes")
    print(f"New app.py: {os.path.getsize(new_app):,} bytes")
    print()

    # Step 1: Backup old app.py
    print(f"1. Backing up app.py to {os.path.basename(backup_app)}")
    shutil.copy2(old_app, backup_app)

    # Step 2: Replace app.py with app_new.py
    print("2. Replacing app.py with new modular version")
    shutil.move(new_app, old_app)

    # Step 3: Update __init__.py if needed
    init_file = os.path.join(cli_dir, "__init__.py")
    if os.path.exists(init_file):
        print("3. Checking __init__.py")
        with open(init_file) as f:
            content = f.read()

        # Ensure proper imports
        if "from .app import cli" not in content:
            print("   - Updating imports")
            with open(init_file, 'w') as f:
                f.write("""\"\"\"Flow CLI package.\"\"\"

from .app import cli


def main():
    \"\"\"Entry point for the CLI.\"\"\"
    cli(prog_name="flow")


__all__ = ["cli", "main"]
""")

    print()
    print("Migration complete!")
    print(f"Old app.py backed up to: {backup_app}")
    print("The CLI now uses a modular command structure.")
    print()
    print("Next steps:")
    print("1. Test the CLI thoroughly: flow --help")
    print("2. Port remaining commands to the modular structure")
    print("3. Remove the backup file once confirmed working")


if __name__ == "__main__":
    migrate_cli()
