#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "typer",
#     "httpx",
# ]
# ///
"""
Resume an existing agent orchestrator session.

This command creates a run to resume a previous session with a new prompt.

Configuration:
    AGENT_ORCHESTRATOR_API_URL: API base URL (default: http://localhost:8765)
"""

import sys
from pathlib import Path

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

import typer
from typing import Optional

app = typer.Typer(add_completion=False)


@app.command()
def main(
    session_name: str = typer.Argument(..., help="Name of the session"),
    prompt: Optional[str] = typer.Option(None, "-p", "--prompt", help="Continuation prompt"),
):
    """
    Resume an existing agent orchestrator session.

    Examples:
        ao-resume mysession -p "Add error handling"
        cat additional-requirements.md | ao-resume mysession
    """
    from config import get_api_url
    from run_client import RunClient, RunClientError, RunFailedError, RunTimeoutError
    from utils import (
        get_prompt_from_args_and_stdin,
        error_exit,
    )

    try:
        # 1. Get API URL
        api_url = get_api_url()

        # 2. Get prompt (from -p and/or stdin)
        user_prompt = get_prompt_from_args_and_stdin(prompt)

        # 3. Create resume run and wait for result
        run_client = RunClient(api_url)
        result = run_client.resume_session(
            session_name=session_name,
            prompt=user_prompt,
        )

        # 4. Print result to stdout
        print(result)

    except RunFailedError as e:
        error_exit(str(e))
    except RunTimeoutError as e:
        error_exit(str(e))
    except RunClientError as e:
        error_exit(str(e))
    except ValueError as e:
        # Prompt errors, etc.
        error_exit(str(e))
    except Exception as e:
        # Unexpected errors
        error_exit(f"Unexpected error: {e}")


if __name__ == "__main__":
    app()
