import os
from pathlib import Path
from alembic.config import Config
from alembic import command
from rich.console import Console

console = Console()


class MigrationManager:
    """Manage database migrations with Alembic"""
    
    def __init__(self, db_url: str = None):
        self.db_url = db_url or os.environ.get('DATABASE_URL', 'sqlite:///app.db')
        self.migrations_dir = Path('migrations')
        self.alembic_ini = Path('alembic.ini')
    
    def init(self):
        """Initialize migrations directory"""
        if self.migrations_dir.exists():
            console.print("[yellow]Migrations directory already exists[/yellow]")
            return
        
        console.print("[cyan]Initializing migrations...[/cyan]")
        
        alembic_ini_content = f"""[alembic]
script_location = migrations
sqlalchemy.url = {self.db_url}

[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
"""
        
        with open(self.alembic_ini, 'w') as f:
            f.write(alembic_ini_content)
        
        alembic_cfg = Config(str(self.alembic_ini))
        command.init(alembic_cfg, str(self.migrations_dir))
        
        console.print("[green]✓ Migrations initialized successfully![/green]")
    
    def create(self, message: str):
        """Create a new migration"""
        console.print(f"[cyan]Creating migration: {message}[/cyan]")
        
        alembic_cfg = Config(str(self.alembic_ini))
        command.revision(alembic_cfg, message=message, autogenerate=True)
        
        console.print("[green]✓ Migration created successfully![/green]")
    
    def upgrade(self, revision: str = 'head'):
        """Upgrade database to a revision"""
        console.print(f"[cyan]Upgrading database to {revision}...[/cyan]")
        
        alembic_cfg = Config(str(self.alembic_ini))
        command.upgrade(alembic_cfg, revision)
        
        console.print("[green]✓ Database upgraded successfully![/green]")
    
    def downgrade(self, revision: str = '-1'):
        """Downgrade database to a revision"""
        console.print(f"[cyan]Downgrading database to {revision}...[/cyan]")
        
        alembic_cfg = Config(str(self.alembic_ini))
        command.downgrade(alembic_cfg, revision)
        
        console.print("[green]✓ Database downgraded successfully![/green]")
    
    def current(self):
        """Show current revision"""
        alembic_cfg = Config(str(self.alembic_ini))
        command.current(alembic_cfg)
    
    def history(self):
        """Show migration history"""
        alembic_cfg = Config(str(self.alembic_ini))
        command.history(alembic_cfg)
