"""Solve command - submit a problem image and get a solution."""

import json

import httpx
import typer
from rich.console import Console
from rich.panel import Panel
from rich.spinner import Spinner
from rich.live import Live

from gpai_cli.client import GPAIClient
from gpai_cli.solve_core import run_solve

console = Console()


def solve(
    image: str = typer.Argument(help="Path to problem image or URL"),
    output_json: bool = typer.Option(False, "--json", help="Output as JSON"),
    output_file: str | None = typer.Option(None, "-o", "--output", help="Save to file"),
    debug: bool = typer.Option(False, "--debug", help="Show raw API response"),
) -> None:
    """Solve a math/science problem from an image."""
    try:
        client = GPAIClient()
    except RuntimeError as e:
        console.print(f"[red]{e}[/red]")
        raise typer.Exit(1)

    with Live(Spinner("dots", text="Solving..."), console=console, transient=True):
        try:
            result = run_solve(client, image)
        except httpx.HTTPStatusError as e:
            console.print(f"[red]API error: {e.response.status_code} {e.response.text}[/red]")
            raise typer.Exit(1)
        except Exception as e:
            console.print(f"[red]Error: {e}[/red]")
            raise typer.Exit(1)

    if debug:
        console.print("[dim]Raw response:[/dim]")
        console.print(json.dumps(result["raw_response"], ensure_ascii=False, indent=2)[:3000])
        console.print()

    answer = result["answer"] or "N/A"
    content = result["solution"] or "No solution available"
    visuals = result["visuals"]

    # JSON output
    if output_json:
        out = {
            "answer": answer,
            "solution": content,
            "visuals": visuals,
            "image_url": result["image_url"],
            "task_id": result["task_id"],
        }
        output = json.dumps(out, ensure_ascii=False, indent=2)
        if output_file:
            with open(output_file, "w") as f:
                f.write(output)
            console.print(f"[green]Saved to {output_file}[/green]")
        else:
            print(output)
        return

    # Pretty output
    console.print()
    console.print(Panel(f"[bold green]{answer}[/bold green]", title="Answer"))
    console.print()
    console.print(Panel(content, title="Solution"))

    for i, url in enumerate(visuals, 1):
        console.print(f"\n[dim]Visual {i}:[/dim] {url}")

    # Save to file if requested
    if output_file:
        with open(output_file, "w") as f:
            f.write(f"# Answer\n\n{answer}\n\n# Solution\n\n{content}\n")
            for i, url in enumerate(visuals, 1):
                f.write(f"\n![Visual {i}]({url})\n")
        console.print(f"\n[green]Saved to {output_file}[/green]")
