#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "typer",
#     "httpx",
# ]
# ///
"""
Extract the result from a completed agent orchestrator session.
"""

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent / "lib"))

import typer

app = typer.Typer(add_completion=False)


@app.command()
def main(
    session_name: str = typer.Argument(..., help="Name of the session"),
):
    """
    Extract the result from a completed session.

    Examples:
        ao-get-result mysession
    """
    from config import get_api_url
    from session_client import SessionClient, SessionClientError

    try:
        api_url = get_api_url()
        client = SessionClient(api_url)

        session = client.get_session_by_name(session_name)
        if not session:
            print(f"Error: Session '{session_name}' does not exist", file=sys.stderr)
            raise typer.Exit(1)

        status = client.get_status(session['session_id'])
        if status == "running":
            print(f"Error: Session '{session_name}' is still running. Wait for completion or check status with ao-status.", file=sys.stderr)
            raise typer.Exit(1)

        result = client.get_result(session['session_id'])
        print(result)

    except SessionClientError as e:
        print(f"Error: {e}", file=sys.stderr)
        raise typer.Exit(1)
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        raise typer.Exit(1)


if __name__ == "__main__":
    app()
