"""Ollama backend CLI command (#16).

``sage-llm ollama`` provides a set of sub-commands for interacting with
a locally-running Ollama server as an alternative backend.

Sub-commands
------------
- ``sage-llm ollama status``       — check Ollama health and version
- ``sage-llm ollama list``         — list available local models
- ``sage-llm ollama run -p TEXT``  — generate text via Ollama
- ``sage-llm ollama chat -p TEXT`` — multi-turn chat via Ollama

Issue
-----
#16 Implement Ollama backend
"""

from __future__ import annotations

import click

from sagellm.ollama_client import OllamaClient

from ..utils.console import get_console

_DEFAULT_URL = "http://localhost:11434"


@click.group()
@click.option(
    "--url",
    default=_DEFAULT_URL,
    show_default=True,
    help="Ollama server URL.",
)
@click.option(
    "--model",
    "-m",
    default="llama3",
    show_default=True,
    help="Default Ollama model.",
)
@click.pass_context
def ollama(ctx: click.Context, url: str, model: str) -> None:
    """Interact with a local Ollama server as an inference backend.

    \b
    Examples:
        sage-llm ollama status
        sage-llm ollama list
        sage-llm ollama run -p "What is 2+2?"
        sage-llm ollama chat -p "Hello!"
    """
    ctx.ensure_object(dict)
    ctx.obj["ollama_url"] = url
    ctx.obj["ollama_model"] = model


@ollama.command("status")
@click.pass_context
def ollama_status(ctx: click.Context) -> None:
    """Check Ollama server health and version."""
    console = get_console()
    client = OllamaClient(
        base_url=ctx.obj["ollama_url"],
        model=ctx.obj["ollama_model"],
    )
    if client.health():
        ver = client.version()
        console.print(f"[green]Ollama is running[/green]  (version: {ver})")
        console.print(f"URL: {client.base_url}")
    else:
        console.print(
            f"[red]Ollama is NOT reachable[/red] at {client.base_url}\n"
            "Tip: start Ollama with `ollama serve`"
        )
        raise SystemExit(1)


@ollama.command("list")
@click.pass_context
def ollama_list(ctx: click.Context) -> None:
    """List locally available Ollama models."""
    console = get_console()
    client = OllamaClient(
        base_url=ctx.obj["ollama_url"],
        model=ctx.obj["ollama_model"],
    )
    models = client.list_models()
    if models:
        console.print("[bold]Locally available Ollama models:[/bold]")
        for m in models:
            console.print(f"  • {m}")
    else:
        console.print("No models found. Pull one with: ollama pull <model-name>")


@ollama.command("run")
@click.option("--prompt", "-p", required=True, help="Input prompt.")
@click.option("--max-tokens", default=128, show_default=True, help="Max output tokens.")
@click.option("--temperature", "-t", default=0.0, show_default=True, help="Sampling temperature.")
@click.pass_context
def ollama_run(ctx: click.Context, prompt: str, max_tokens: int, temperature: float) -> None:
    """Run a single text completion via Ollama.

    \b
    Examples:
        sage-llm ollama run -p "Tell me a joke"
        sage-llm ollama run -p "Write code" --temperature 0.7
    """
    console = get_console()
    client = OllamaClient(
        base_url=ctx.obj["ollama_url"],
        model=ctx.obj["ollama_model"],
    )
    console.print(f"[dim]Sending to Ollama ({ctx.obj['ollama_model']})...[/dim]")
    resp = client.complete(prompt, max_tokens=max_tokens, temperature=temperature)
    console.print("\n[bold]Response:[/bold]")
    console.print(resp["text"])
    usage = resp.get("usage", {})
    if usage:
        console.print(
            f"\n[dim]Tokens: prompt={usage.get('prompt_tokens', '?')} "
            f"completion={usage.get('completion_tokens', '?')}[/dim]"
        )


@ollama.command("chat")
@click.option("--prompt", "-p", required=True, help="User message.")
@click.option("--system", "-s", default=None, help="Optional system message.")
@click.option("--max-tokens", default=128, show_default=True, help="Max output tokens.")
@click.option("--temperature", "-t", default=0.7, show_default=True, help="Sampling temperature.")
@click.pass_context
def ollama_chat(
    ctx: click.Context,
    prompt: str,
    system: str | None,
    max_tokens: int,
    temperature: float,
) -> None:
    """Send a chat message to Ollama.

    \b
    Examples:
        sage-llm ollama chat -p "Hello!"
        sage-llm ollama chat -p "Explain Python" --system "You are a teacher."
    """
    console = get_console()
    client = OllamaClient(
        base_url=ctx.obj["ollama_url"],
        model=ctx.obj["ollama_model"],
    )
    messages: list[dict[str, str]] = []
    if system:
        messages.append({"role": "system", "content": system})
    messages.append({"role": "user", "content": prompt})

    console.print(f"[dim]Chatting with Ollama ({ctx.obj['ollama_model']})...[/dim]")
    resp = client.chat(messages, max_tokens=max_tokens, temperature=temperature)
    console.print("\n[bold]Response:[/bold]")
    console.print(resp["text"])
