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

This command creates a run to start a new Claude AI session via the Agent Coordinator.

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

import sys
from pathlib import Path

# Add lib to path for shared modules
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="Session prompt"),
    agent: Optional[str] = typer.Option(None, "--agent", help="Agent to use"),
    project_dir: Optional[Path] = typer.Option(None, "--project-dir", help="Project directory"),
):
    """
    Start a new agent orchestrator session.

    Examples:
        ao-start mysession -p "Write hello world"
        ao-start research --agent web-researcher -p "Research AI"
        cat prompt.md | ao-start mysession
    """
    from config import load_config
    from agent_api import get_agent_api, AgentAPIError
    from run_client import RunClient, RunClientError, RunFailedError, RunTimeoutError
    from utils import (
        get_prompt_from_args_and_stdin,
        error_exit,
    )

    try:
        # 1. Load configuration
        config = load_config(
            cli_project_dir=str(project_dir) if project_dir else None,
        )

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

        # 3. Validate agent exists if specified
        agent_name = None
        if agent:
            try:
                agent_data = get_agent_api(agent)
            except AgentAPIError as e:
                error_exit(str(e))

            if not agent_data:
                error_exit(f"Agent not found: {agent}")

            if agent_data.get("status") == "inactive":
                error_exit(f"Agent '{agent}' is inactive")

            agent_name = agent_data.get("name")

        # 4. Create run and wait for result
        run_client = RunClient(config.api_url)
        result = run_client.start_session(
            session_name=session_name,
            prompt=user_prompt,
            agent_name=agent_name,
            project_dir=str(config.project_dir),
        )

        # 5. 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()
