"""caprail make migration <name>"""
from __future__ import annotations
from datetime import datetime
from pathlib import Path
import typer
from rich.console import Console

console = Console()

TEMPLATE = '''"""
{class_name} migration.
"""
from __future__ import annotations

from caprail.orm.migrations import Migration, Schema


class {class_name}(Migration):

    async def up(self, schema: Schema) -> None:
        await schema.create("{table}", lambda table: [
            table.id(),
            table.timestamps(),
        ])

    async def down(self, schema: Schema) -> None:
        await schema.drop_if_exists("{table}")
'''

def _class_name(name: str) -> str:
    return "".join(part.capitalize() for part in name.split("_"))

def _table_from_name(name: str) -> str:
    name = name.removeprefix("create_").removesuffix("_table")
    return name

def _create(name: str) -> None:
    ts = datetime.utcnow().strftime("%Y_%m_%d_%H%M%S")
    filename = f"{ts}_{name}.py"
    dest = Path.cwd() / "database" / "migrations" / filename
    dest.parent.mkdir(parents=True, exist_ok=True)
    cls = _class_name(name)
    table = _table_from_name(name)
    dest.write_text(TEMPLATE.format(class_name=cls, table=table))
    console.print(f"[green]Migration created:[/] {dest}")

def command(
    name: str = typer.Argument(..., help="Migration name (snake_case)"),
) -> None:
    """Generate a new database migration."""
    _create(name)
