"""CLI entry point — banner, argument parsing, and startup orchestration."""

import argparse
import sys
import threading
import time
import webbrowser
from pathlib import Path

import uvicorn
from rich.console import Console

from hangar.dependencies import set_project_path, get_project_path
from hangar.installer import install_skills_standalone, run_wizard
from hangar.main import STATIC_DIR

console = Console()

VERSION = "0.1.1"

BANNER_LINES = [
    "  ██╗  ██╗ █████╗ ███╗   ██╗ ██████╗  █████╗ ██████╗ ",
    "  ██║  ██║██╔══██╗████╗  ██║██╔════╝ ██╔══██╗██╔══██╗",
    "  ███████║███████║██╔██╗ ██║██║  ███╗███████║██████╔╝",
    "  ██╔══██║██╔══██║██║╚██╗██║██║   ██║██╔══██║██╔══██╗",
    "  ██║  ██║██║  ██║██║ ╚████║╚██████╔╝██║  ██║██║  ██║",
    "  ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═══╝ ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝",
]

# Gradient from cyan through blue-purple to purple
GRADIENT_COLORS = [
    "#7dd3fc",  # cyan
    "#93c5fd",  # light blue
    "#a5b4fc",  # indigo
    "#a78bfa",  # violet
    "#a78bfa",  # violet
    "#c084fc",  # purple
]


def print_banner() -> None:
    """Print the ASCII art banner with a cyan→purple gradient."""
    console.print()
    for i, line in enumerate(BANNER_LINES):
        color = GRADIENT_COLORS[i % len(GRADIENT_COLORS)]
        console.print(f"[{color}]{line}[/{color}]")
    console.print()
    console.print(f"  [dim]orchestration-first ide[/dim]{'':>25}[dim]v{VERSION}[/dim]")
    console.print()


def build_parser() -> argparse.ArgumentParser:
    """Build the argument parser."""
    parser = argparse.ArgumentParser(
        prog="hangar",
        description="Hangar — Orchestration IDE",
    )
    parser.add_argument(
        "project_path",
        nargs="?",
        help="Project directory (default: auto-discover)",
    )
    parser.add_argument("--port", "-p", type=int, default=8000)
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--no-open", action="store_true", help="Don't open browser")
    parser.add_argument("--dev", action="store_true", help="Dev mode (auto-reload)")
    parser.add_argument(
        "--install-skills",
        nargs="?",
        const="",
        metavar="PATH",
        help="Install agent skills to project dir (or PATH), then exit",
    )
    parser.add_argument(
        "--no-install",
        action="store_true",
        help="Skip the skill installation wizard",
    )
    return parser


def main() -> None:
    """Main entry point for the hangar CLI."""
    parser = build_parser()
    args = parser.parse_args()

    # Set project path if provided
    if args.project_path:
        set_project_path(Path(args.project_path).resolve())

    project_path = get_project_path()

    # --install-skills: utility mode, install and exit
    if args.install_skills is not None:
        target = Path(args.install_skills).resolve() if args.install_skills else project_path
        print_banner()
        install_skills_standalone(target)
        sys.exit(0)

    # Normal startup: banner + optional wizard
    print_banner()

    short_path = str(project_path).replace(str(Path.home()), "~")
    console.print(f"  Project: [bold white]{short_path}[/bold white]")

    if not args.no_install:
        run_wizard(project_path)

    # Auto-open browser if static files are bundled
    if not args.no_open and STATIC_DIR.is_dir():
        threading.Thread(
            target=lambda: (time.sleep(0.8), webbrowser.open(f"http://{args.host}:{args.port}")),
            daemon=True,
        ).start()

    url = f"http://{args.host}:{args.port}"
    console.print(f"  [green]Starting Hangar on {url} ...[/green]\n")

    uvicorn.run(
        "hangar.main:app",
        host=args.host,
        port=args.port,
        reload=args.dev,
        log_level="info",
    )
