"""caprail make model <Name>"""
from __future__ import annotations
from pathlib import Path
import typer
from rich.console import Console

console = Console()

TEMPLATE = '''"""
{name} model.
"""
from __future__ import annotations

from caprail.orm.model import Model
from caprail.orm import relations


class {name}(Model):
    table = "{table}"
    fillable = []
    hidden = ["password"] if "password" in fillable else []
    timestamps = True
'''

def command(
    name: str = typer.Argument(..., help="Model class name"),
    migration: bool = typer.Option(False, "--migration", "-m", help="Also create a migration"),
) -> None:
    """Generate a new Eloquent-like model."""
    dest = Path.cwd() / "app" / "Models" / f"{name}.py"
    dest.parent.mkdir(parents=True, exist_ok=True)
    if dest.exists():
        console.print(f"[yellow]Model already exists:[/] {dest}")
        raise typer.Exit(1)

    import re
    table = re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower() + "s"
    dest.write_text(TEMPLATE.format(name=name, table=table))
    console.print(f"[green]Model created:[/] {dest}")

    if migration:
        from caprail.console.commands import make_migration
        make_migration._create(f"create_{table}_table")
