"""Query account information: positions, orders, fills, account."""

from typing import Annotated, Any

import typer

from ..config import OutputFormat
from ..context import AppContext
from ..output import format_fills, format_orders, format_positions
from .base import console, safe_command, with_progress

app = typer.Typer(help="Query account information", rich_markup_mode="rich")


@app.command("positions")
@safe_command
def query_positions(
    ctx: typer.Context,
    address: Annotated[str | None, typer.Argument(help="Wallet address (defaults to configured address)")] = None,
) -> None:
    """Get open positions for any wallet address."""
    app_ctx: AppContext = ctx.obj

    target_address = address or app_ctx.config.account_address
    if not target_address:
        console.print("[red]No address provided and no configured address found[/red]")
        raise typer.Exit(code=1) from None

    @with_progress("Fetching positions...")
    def execute() -> Any:
        user_state = app_ctx.client.get_user_state(target_address)
        return user_state.get("assetPositions", [])

    positions = execute()

    if app_ctx.formatter.format == OutputFormat.JSON:
        app_ctx.formatter.print(positions)
    else:
        formatted_positions = format_positions(positions)
        if not formatted_positions:
            console.print(f"[yellow]No open positions found for {target_address}[/yellow]")
        else:
            app_ctx.formatter.print(formatted_positions, title=f"Positions for {target_address[:10]}...")


@app.command("orders")
@safe_command
def query_orders(
    ctx: typer.Context,
    address: Annotated[str | None, typer.Argument(help="Wallet address (defaults to configured address)")] = None,
) -> None:
    """Get open orders for any wallet address."""
    app_ctx: AppContext = ctx.obj

    target_address = address or app_ctx.config.account_address
    if not target_address:
        console.print("[red]No address provided and no configured address found[/red]")
        raise typer.Exit(code=1) from None

    @with_progress("Fetching open orders...")
    def execute() -> Any:
        return app_ctx.client.get_open_orders(target_address)

    orders = execute()

    if app_ctx.formatter.format == OutputFormat.JSON:
        app_ctx.formatter.print(orders)
    else:
        formatted_orders = format_orders(orders)
        if not formatted_orders:
            console.print(f"[yellow]No open orders found for {target_address}[/yellow]")
        else:
            app_ctx.formatter.print(formatted_orders, title=f"Open Orders for {target_address[:10]}...")


@app.command("fills")
@safe_command
def query_fills(
    ctx: typer.Context,
    address: Annotated[str | None, typer.Argument(help="Wallet address (defaults to configured address)")] = None,
) -> None:
    """Get recent trade fills for any wallet address."""
    app_ctx: AppContext = ctx.obj

    target_address = address or app_ctx.config.account_address
    if not target_address:
        console.print("[red]No address provided and no configured address found[/red]")
        raise typer.Exit(code=1) from None

    @with_progress("Fetching recent fills...")
    def execute() -> Any:
        return app_ctx.client.get_user_fills(target_address)

    fills = execute()

    if app_ctx.formatter.format == OutputFormat.JSON:
        app_ctx.formatter.print(fills)
    else:
        formatted_fills = format_fills(fills)
        if not formatted_fills:
            console.print(f"[yellow]No fills found for {target_address}[/yellow]")
        else:
            app_ctx.formatter.print(formatted_fills, title=f"Recent Fills for {target_address[:10]}...")


@app.command("account")
@safe_command
def query_account(
    ctx: typer.Context,
    address: Annotated[str | None, typer.Argument(help="Wallet address (defaults to configured address)")] = None,
) -> None:
    """Get account summary including balances and margin for any wallet address."""
    app_ctx: AppContext = ctx.obj

    target_address = address or app_ctx.config.account_address
    if not target_address:
        console.print("[red]No address provided and no configured address found[/red]")
        raise typer.Exit(code=1) from None

    @with_progress("Fetching account information...")
    def execute() -> Any:
        return app_ctx.client.get_user_state(target_address)

    user_state = execute()

    if app_ctx.formatter.format == OutputFormat.JSON:
        app_ctx.formatter.print(user_state)
    else:
        margin_summary = user_state.get("marginSummary", {})
        cross_margin_summary = user_state.get("crossMarginSummary", {})

        account_data = []
        if margin_summary:
            account_data.append(
                {"Field": "Account Value", "Value": f"${float(margin_summary.get('accountValue', 0)):,.2f}"}
            )
            account_data.append(
                {"Field": "Total Margin Used", "Value": f"${float(margin_summary.get('totalMarginUsed', 0)):,.2f}"}
            )
            account_data.append(
                {"Field": "Total Notional", "Value": f"${float(margin_summary.get('totalNtlPos', 0)):,.2f}"}
            )
            account_data.append(
                {"Field": "Total Raw USD", "Value": f"${float(margin_summary.get('totalRawUsd', 0)):,.2f}"}
            )

        if cross_margin_summary:
            account_data.append(
                {"Field": "Cross Account Value", "Value": f"${float(cross_margin_summary.get('accountValue', 0)):,.2f}"}
            )
            account_data.append(
                {
                    "Field": "Cross Total Margin Used",
                    "Value": f"${float(cross_margin_summary.get('totalMarginUsed', 0)):,.2f}",
                }
            )

        if account_data:
            app_ctx.formatter.print(account_data, title=f"Account Summary for {target_address[:10]}...")
        else:
            console.print(f"[yellow]No account data found for {target_address}[/yellow]")
