"""
Module: status
Description: Display comprehensive environment status

Implements:
    - docs/cli/reference.md#huitzo-status
    - docs/guides/billing.md#checking-your-tier

See Also:
    - docs/guides/quickstart/installation.md (references huitzo status)
"""

from __future__ import annotations

import json
import logging
from typing import Any

import httpx
import typer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

from huitzo_cli.auth import AuthClient
from huitzo_cli.config import ConfigManager
from huitzo_cli.validator import PackValidator

logger = logging.getLogger(__name__)
console = Console()


def _collect_identity(auth: AuthClient) -> dict[str, Any]:
    """Collect identity/authentication data."""
    if not auth.is_authenticated():
        return {"authenticated": False}

    user = auth.get_current_user()
    if user:
        return {
            "authenticated": True,
            "email": user.get("email"),
            "role": user.get("role"),
            "subscription_tier": user.get("subscriptionTier"),
            "org": user.get("tenantSlug"),
        }
    return {"authenticated": True, "error": "Token expired or server unreachable"}


def _collect_server(api_url: str) -> dict[str, Any]:
    """Collect server connectivity data."""
    try:
        resp = httpx.get(f"{api_url}/health", timeout=5)
        if resp.status_code == 200:
            try:
                health = resp.json()
            except (json.JSONDecodeError, ValueError):
                logger.debug("Health endpoint returned non-JSON response")
                return {"api_url": api_url, "reachable": True, "version": None, "status": None}
            return {
                "api_url": api_url,
                "reachable": True,
                "version": health.get("version"),
                "status": health.get("status"),
            }
        return {"api_url": api_url, "reachable": False, "http_status": resp.status_code}
    except httpx.HTTPError as exc:
        logger.debug("Server health check failed: %s", exc)
        return {"api_url": api_url, "reachable": False}


def _collect_codebase() -> dict[str, Any]:
    """Collect codebase validation data."""
    validator = PackValidator()
    result = validator.validate()
    is_pack_dir = not (
        "pyproject.toml not found" in result.errors and "huitzo.yaml not found" in result.errors
    )
    return {
        "is_pack_directory": is_pack_dir,
        "valid": result.valid,
        "errors": result.errors,
        "warnings": result.warnings,
    }


def _collect_dev_sessions(api_url: str, token: str) -> list[dict[str, Any]] | None:
    """Collect active dev sessions. Returns None on failure."""
    try:
        resp = httpx.get(
            f"{api_url}/api/v1/dev-sessions",
            params={"status": "active"},
            headers={"Authorization": f"Bearer {token}"},
            timeout=10,
        )
        if resp.status_code != 200:
            logger.debug("Dev sessions returned HTTP %s", resp.status_code)
            return None
        try:
            body = resp.json()
        except (json.JSONDecodeError, ValueError):
            logger.debug("Dev sessions returned non-JSON response")
            return None
        sessions = body.get("data", [])
        return [
            {
                "id": s.get("id", "")[:8],
                "pack": s.get("pack_namespace", "unknown"),
                "sandbox_type": s.get("sandbox_type", "unknown"),
                "port": s.get("local_port"),
            }
            for s in sessions
        ]
    except httpx.HTTPError as exc:
        logger.debug("Dev sessions fetch failed: %s", exc)
        return None


def _render_identity(identity: dict[str, Any]) -> None:
    """Render identity panel."""
    if not identity["authenticated"]:
        console.print(
            Panel(
                "[red]Not authenticated[/red]\nRun: [bold]huitzo login[/bold]",
                title="Identity",
                border_style="red",
            )
        )
        return

    if "error" in identity:
        console.print(
            Panel(
                "[yellow]Token found but could not verify[/yellow]\nTry: [bold]huitzo login[/bold]",
                title="Identity",
                border_style="yellow",
            )
        )
        return

    table = Table(show_header=False, box=None, padding=(0, 1))
    table.add_column(style="bold")
    table.add_column()
    table.add_row("Email", identity.get("email", "unknown"))
    table.add_row("Role", identity.get("role", "unknown"))
    table.add_row("Tier", identity.get("subscription_tier", "unknown"))
    table.add_row("Org", identity.get("org", "unknown"))
    console.print(Panel(table, title="Identity", border_style="green"))


def _render_server(server: dict[str, Any]) -> None:
    """Render server panel."""
    api_url = server["api_url"]
    if server.get("reachable"):
        table = Table(show_header=False, box=None, padding=(0, 1))
        table.add_column(style="bold")
        table.add_column()
        table.add_row("API URL", api_url)
        table.add_row("Status", f"[green]{server.get('status', 'ok')}[/green]")
        table.add_row("Version", server.get("version", "unknown"))
        console.print(Panel(table, title="Server", border_style="green"))
    elif "http_status" in server:
        console.print(
            Panel(
                f"API URL:  {api_url}\nStatus:   [red]HTTP {server['http_status']}[/red]",
                title="Server",
                border_style="red",
            )
        )
    else:
        console.print(
            Panel(
                f"API URL:  {api_url}\nStatus:   [red]unreachable[/red]",
                title="Server",
                border_style="red",
            )
        )


def _render_codebase(codebase: dict[str, Any]) -> None:
    """Render codebase panel."""
    if not codebase["is_pack_directory"]:
        console.print(
            Panel(
                "[dim]Not in a pack directory[/dim]",
                title="Codebase",
                border_style="dim",
            )
        )
    elif codebase["valid"]:
        lines = ["[green]Valid Intelligence Pack[/green]"]
        for w in codebase["warnings"]:
            lines.append(f"[yellow]Warning:[/yellow] {w}")
        console.print(Panel("\n".join(lines), title="Codebase", border_style="green"))
    else:
        lines = ["[red]Invalid pack structure[/red]"]
        for e in codebase["errors"]:
            lines.append(f"[red]Error:[/red] {e}")
        for w in codebase["warnings"]:
            lines.append(f"[yellow]Warning:[/yellow] {w}")
        console.print(Panel("\n".join(lines), title="Codebase", border_style="red"))


def _render_dev_sessions(sessions: list[dict[str, Any]] | None) -> None:
    """Render dev sessions panel."""
    if sessions is None:
        console.print(
            Panel(
                "[yellow]Could not fetch dev sessions[/yellow]",
                title="Dev Sessions",
                border_style="yellow",
            )
        )
    elif not sessions:
        console.print(
            Panel(
                "[dim]No active dev sessions[/dim]",
                title="Dev Sessions",
                border_style="dim",
            )
        )
    else:
        table = Table(box=None, padding=(0, 1))
        table.add_column("ID", style="bold")
        table.add_column("Pack")
        table.add_column("Type")
        table.add_column("Port")
        for s in sessions:
            table.add_row(s["id"], s["pack"], s["sandbox_type"], str(s.get("port", "")))
        console.print(Panel(table, title="Dev Sessions", border_style="cyan"))


def _render_quick_reference() -> None:
    """Render quick reference panel."""
    commands = (
        "  huitzo login              Authenticate\n"
        "  huitzo pack new           Create new pack\n"
        "  huitzo pack dev           Start dev session\n"
        "  huitzo pack validate      Validate pack structure\n"
        "  huitzo pack test          Run tests\n"
        "  huitzo pack publish       Publish to registry\n"
        "  huitzo run <cmd>          Run a command"
    )
    console.print(Panel(commands, title="Quick Reference", border_style="blue"))


def status(
    json_output: bool = typer.Option(False, "--json", help="Output as JSON"),
) -> None:
    """Show current authentication, server, and environment status."""
    config = ConfigManager()
    auth = AuthClient(config)
    api_url = auth.get_api_url()
    token = auth.get_token()

    # Collect all data
    identity = _collect_identity(auth)
    server = _collect_server(api_url)
    codebase = _collect_codebase()

    authenticated = identity["authenticated"] and "error" not in identity
    server_reachable = server.get("reachable", False)

    dev_sessions = None
    if authenticated and server_reachable and token:
        dev_sessions = _collect_dev_sessions(api_url, token)

    if json_output:
        data = {
            "identity": identity,
            "server": server,
            "codebase": codebase,
            "dev_sessions": dev_sessions,
        }
        console.print_json(json.dumps(data))
        return

    # Render Rich panels
    _render_identity(identity)
    _render_server(server)
    _render_codebase(codebase)
    if authenticated and server_reachable:
        _render_dev_sessions(dev_sessions)
    _render_quick_reference()
