"""CLI interface for OpenClaw installer."""

from pathlib import Path
from typing import Optional

import typer
from rich import print as rprint

from .installer import OpenClawInstaller

__version__ = "1.0.34"

app = typer.Typer(help="Installer for OpenClaw - installs and starts the gateway")


def version_callback(value: bool):
    if value:
        print(f"openclaw-installer version {__version__}")
        raise typer.Exit()


@app.callback()
def common(
    version: bool = typer.Option(
        False, "--version", "-v", callback=version_callback, is_eager=True,
        help="Show version and exit"
    ),
):
    pass


@app.command()
def install(
    dry_run: bool = typer.Option(False, "--dry-run", help="Simulate without making changes"),
    system_node: bool = typer.Option(False, "--system-node", help="Use system Node.js instead of downloading"),
):
    """Install OpenClaw and start the gateway."""
    installer = OpenClawInstaller(dry_run=dry_run, use_system_node=system_node)
    success = installer.install()
    raise typer.Exit(0 if success else 1)


@app.command()
def uninstall(
    dry_run: bool = typer.Option(False, "--dry-run", help="Simulate without making changes"),
):
    """Uninstall OpenClaw."""
    installer = OpenClawInstaller(dry_run=dry_run)
    success = installer.uninstall()
    raise typer.Exit(0 if success else 1)


@app.command()
def dashboard(
    browser: Optional[str] = typer.Option(None, "--browser", "-b", help="Path to browser executable"),
):
    """Open OpenClaw dashboard."""
    import subprocess
    import sys
    
    if sys.platform == "win32":
        wrapper = Path.home() / "AppData" / "Local" / "openclaw-installer" / "bin" / "openclaw.cmd"
    else:
        wrapper = Path.home() / ".local" / "share" / "openclaw-installer" / "bin" / "openclaw"
    
    if not wrapper.exists():
        rprint("[red]OpenClaw not installed. Run: openclaw-installer install[/]")
        raise typer.Exit(1)
    
    subprocess.run([str(wrapper), "dashboard"])


def main():
    app()


if __name__ == "__main__":
    main()
