"""
Module: dashboard_command
Description: Dashboard management commands

Implements:
    - docs/cli/reference.md#dashboard-commands
"""

import subprocess
from pathlib import Path
from typing import Optional

import typer
from jinja2 import Environment, PackageLoader
from rich.console import Console

console = Console()
dashboard_app = typer.Typer(help="Dashboard operations")


@dashboard_app.command()
def new(
    name: Optional[str] = typer.Argument(None, help="Dashboard name"),
    author: Optional[str] = typer.Option(None, "--author", help="Author name"),
) -> None:
    """Create a new dashboard project.

    Scaffolds a React + TypeScript dashboard using Vite.
    """
    if not name:
        name = typer.prompt("Dashboard name")

    project_root = Path.cwd() / name

    if project_root.exists():
        console.print(f"[red]❌ Directory '{name}' already exists[/red]")
        raise typer.Exit(1)

    project_root.mkdir(parents=True, exist_ok=True)
    src_dir = project_root / "src"
    src_dir.mkdir(parents=True, exist_ok=True)

    # Set up Jinja2
    env = Environment(loader=PackageLoader("huitzo_cli", "templates/dashboard"))

    context = {"dashboard_name": name}

    # Files to create
    files = {
        "package.json.j2": project_root / "package.json",
        "vite.config.ts.j2": project_root / "vite.config.ts",
        "index.html.j2": project_root / "index.html",
        "tsconfig.json.j2": project_root / "tsconfig.json",
        "tsconfig.node.json.j2": project_root / "tsconfig.node.json",
        "main.tsx.j2": src_dir / "main.tsx",
        "App.tsx.j2": src_dir / "App.tsx",
        "index.css.j2": src_dir / "index.css",
        "App.css.j2": src_dir / "App.css",
    }

    for template_name, target_path in files.items():
        template = env.get_template(template_name)
        content = template.render(**context)
        target_path.write_text(content)

    # Create .gitignore
    (project_root / ".gitignore").write_text("node_modules/\n.env.local\ndist/\n.DS_Store\n")

    console.print(f"\n[green]✅ Dashboard '{name}' created![/green]")
    console.print("\n[bold]Next steps:[/bold]")
    console.print(f"  cd {name}")
    console.print("  npm install")
    console.print("  npm run dev")


@dashboard_app.command()
def dev() -> None:
    """Start dashboard development server.

    Starts Vite dev server with hot module replacement.
    """
    console.print("[bold]Starting dashboard dev server...[/bold]")

    try:
        result = subprocess.run(["npm", "run", "dev"], check=False)
        if result.returncode != 0:
            raise typer.Exit(result.returncode)
    except FileNotFoundError:
        console.print("[red]npm not found. Install Node.js from nodejs.org[/red]")
        raise typer.Exit(1)


@dashboard_app.command()
def build() -> None:
    """Build dashboard for production.

    Creates optimized production build in dist/ directory.
    """
    console.print("[bold]Building dashboard for production...[/bold]")

    try:
        result = subprocess.run(["npm", "run", "build"], check=False)
        if result.returncode == 0:
            console.print("[green]✅ Build successful. Output in dist/[/green]")
        else:
            raise typer.Exit(result.returncode)
    except FileNotFoundError:
        console.print("[red]❌ npm not found[/red]")
        raise typer.Exit(1)


@dashboard_app.command()
def publish() -> None:
    """Publish dashboard to Huitzo Hub.

    Note: Requires Huitzo Cloud (not yet available).
    """
    console.print("[yellow]ℹ️  Huitzo Hub is not yet available[/yellow]")
    console.print("This feature is coming soon!")
    raise typer.Exit(1)


@dashboard_app.command()
def grant(
    user: str = typer.Option(..., "--user", help="User email to grant access"),
) -> None:
    """Grant dashboard access to another user.

    Note: Requires Huitzo Cloud (not yet available).

    Args:
        user: Email of user to grant access
    """
    console.print("[yellow]ℹ️  Huitzo Hub is not yet available[/yellow]")
    console.print("This feature is coming soon!")
    raise typer.Exit(1)


@dashboard_app.command()
def share() -> None:
    """Share dashboard.

    Note: Requires Huitzo Cloud (not yet available).
    """
    console.print("[yellow]ℹ️  Huitzo Hub is not yet available[/yellow]")
    console.print("This feature is coming soon!")
    raise typer.Exit(1)
