"""Main CLI application for Purrio."""

from typing import Annotated

import typer
from rich.console import Console

from . import __version__
from .client import HyperliquidClient
from .commands import config as config_cmd
from .commands import data as data_cmd
from .commands import market as market_cmd
from .commands import orders as orders_cmd
from .commands import query as query_cmd
from .config import OutputFormat, load_config
from .context import AppContext
from .output import OutputFormatter

console = Console()
error_console = Console(stderr=True)

app = typer.Typer(
    name="purrio",
    help="[bold cyan]Purrio CLI[/bold cyan] - Agent-first trading interface for Hyperliquid",
    add_completion=True,
    no_args_is_help=True,
    pretty_exceptions_enable=False,
    rich_markup_mode="rich",
)


@app.callback()
def main_callback(
    ctx: typer.Context,
    output: Annotated[
        OutputFormat | None,
        typer.Option(
            "--output", "-o", help="Output format: [green]table[/green], [yellow]json[/yellow], or [blue]csv[/blue]"
        ),
    ] = None,
    verbose: Annotated[bool, typer.Option("--verbose", "-v", help="Enable verbose output")] = False,
) -> None:
    """
    Initialize application context for all commands.

    This callback runs before any command and sets up the shared context.
    """
    # Initialize configuration
    try:
        config = load_config()
    except Exception as e:
        console.print(f"[red]Error loading configuration:[/red] {e}")
        raise typer.Exit(code=1) from None

    # Override output format if specified
    if output:
        config.output_format = output

    # Initialize client
    try:
        client = HyperliquidClient(config)
    except Exception as e:
        console.print(f"[red]Error initializing client:[/red] {e}")
        raise typer.Exit(code=1) from None

    # Initialize formatter
    formatter = OutputFormatter(config.output_format)

    # Create and store context
    ctx.obj = AppContext(config=config, client=client, formatter=formatter)

    # Store verbose flag for commands to use
    ctx.meta["verbose"] = verbose


app.add_typer(query_cmd.app)
app.add_typer(data_cmd.app)
app.add_typer(market_cmd.app)
app.add_typer(orders_cmd.app, name="limit")
app.add_typer(config_cmd.app, name="config")


@app.command("version")
def version() -> None:
    """Show CLI version."""
    typer.echo(f"Purrio CLI v{__version__}")


def main() -> None:
    """Main entry point for the CLI."""
    try:
        app()
    except KeyboardInterrupt:
        console.print("\n[yellow]Interrupted by user[/yellow]")
        raise typer.Exit(code=130) from None
    except Exception as e:
        console.print(f"[red]Unexpected error:[/red] {e}")
        raise typer.Exit(code=1) from None


if __name__ == "__main__":
    main()
