from __future__ import annotations

from typing import Optional


def _build_orchestra_send_endpoint(agent_url: str, agent_id: Optional[str]) -> str:
    """
    Build final orchestra send endpoint.

    Supports:
    - Base URL + agent_id: .../sendmessage + "123" -> .../sendmessage/123/send
    - Agent URL with encoded ID: .../sendmessage/123 -> .../sendmessage/123/send
    - Agent card URL: .../sendmessage/123/.well-known/agent-card.json -> .../sendmessage/123/send
    - Direct send URL: .../sendmessage/123/send (unchanged)
    """
    base = agent_url.strip().rstrip("/")

    marker = "/.well-known/agent-card.json"
    if marker in base:
        base = base.split(marker, 1)[0].rstrip("/")

    if base.endswith("/send"):
        return base

    if agent_id:
        return f"{base}/{agent_id}/send"

    # If agent ID is already embedded in URL, append /send directly.
    # Example: .../sendmessage/103219967 -> .../sendmessage/103219967/send
    if "/sendmessage/" in base:
        return f"{base}/send"

    raise ValueError(
        "Could not resolve agent send endpoint. Provide either agent_id or "
        "an agent_url that already includes the agent path."
    )
