"""caprail key:generate"""
from __future__ import annotations
import os
import secrets
from pathlib import Path
import typer
from rich.console import Console

console = Console()

def command(
    show: bool = typer.Option(False, "--show", help="Print the key instead of writing to .env"),
) -> None:
    """Generate a new application key."""
    key = "base64:" + secrets.token_urlsafe(32)
    if show:
        console.print(f"[cyan]{key}[/]")
        return

    env_file = Path.cwd() / ".env"
    if env_file.exists():
        content = env_file.read_text()
        if "APP_KEY=" in content:
            import re
            content = re.sub(r"APP_KEY=.*", f"APP_KEY={key}", content)
        else:
            content += f"\nAPP_KEY={key}\n"
        env_file.write_text(content)
        console.print(f"[green]Application key set:[/] {key}")
    else:
        console.print(f"[yellow].env not found. Key:[/] {key}")
