"""A complete custom-tools client for the HKGAI Agent Workshop API.

The agent gets two tools that run here, on your machine, not on the platform:

- get_order_status: looks an order up in a local table (stands in for your own system);
- request_refund:   asks the person at the terminal to approve the refund first.

When the agent calls one, the turn pauses at `turn.requires_action`; this script runs the
tool and sends `user.custom_tool_result`, and the turn goes on.

    pip install httpx
    export AXON_API="https://agent.hkgai.net/open/api/v1"
    export AXON_KEY="sk-..."
    python custom_tools.py                       # chat; an empty line quits
    python custom_tools.py "Where is order A1001?"
"""

import json
import os
import sys
import uuid

import httpx

API = os.environ["AXON_API"].rstrip("/")
HEADERS = {"Authorization": f"Bearer {os.environ['AXON_KEY']}"}
MODEL = os.environ.get("AXON_MODEL", "deepseek-v4-flash")
TERMINAL = {"turn.completed", "turn.failed", "turn.cancelled"}

# ---------------------------------------------------------------------------
# The tools: what the agent sees, and the functions that carry them out.
# ---------------------------------------------------------------------------

ORDERS = {
    "A1001": {"status": "shipped", "carrier": "SF Express", "tracking": "SF2026102801", "total": 299},
    "A1002": {"status": "processing", "carrier": None, "tracking": None, "total": 1280},
}

CUSTOM_TOOLS = [
    {
        "name": "get_order_status",
        "description": "Look up an order by its number: its status, carrier, tracking number "
        "and total. Use it whenever the user asks about an order.",
        "input_schema": {
            "type": "object",
            "properties": {"order_id": {"type": "string", "description": "e.g. A1001"}},
            "required": ["order_id"],
        },
    },
    {
        "name": "request_refund",
        "description": "Refund an order. A person approves every refund, so the result says "
        "whether it was approved.",
        "input_schema": {
            "type": "object",
            "properties": {
                "order_id": {"type": "string"},
                "reason": {"type": "string", "description": "Why the user wants the refund."},
            },
            "required": ["order_id", "reason"],
        },
    },
]


def get_order_status(order_id: str) -> str:
    order = ORDERS.get(order_id.strip().upper())
    if order is None:
        raise ValueError(f"no order {order_id!r}")
    return json.dumps({"order_id": order_id, **order})


def request_refund(order_id: str, reason: str) -> str:
    if order_id.strip().upper() not in ORDERS:
        raise ValueError(f"no order {order_id!r}")
    # The turn waits, holding nothing, for as long as the person takes.
    answer = input(f"\n[approve refund of {order_id} ({reason})? y/n] ").strip().lower()
    return "approved: the refund is on its way" if answer == "y" else "declined by the reviewer"


TOOLS = {"get_order_status": get_order_status, "request_refund": request_refund}


def run_tool(call: dict) -> dict:
    """Carry out one `agent.custom_tool_use`; return its `user.custom_tool_result`."""
    try:
        content, is_error = TOOLS[call["name"]](**call["input"]), False
    except Exception as exc:  # report the failure: the agent reads it and adjusts
        content, is_error = f"{type(exc).__name__}: {exc}", True
    print(f"\n[{call['name']}({call['input']}) -> {content}]")
    return {
        "type": "user.custom_tool_result",
        "tool_use_id": call["id"],
        "content": content,
        "is_error": is_error,
    }


# ---------------------------------------------------------------------------
# The event stream: SSE frames, resumed by `since` and filled from the history.
# ---------------------------------------------------------------------------


def sse_events(response):
    frame = {}
    for line in response.iter_lines():
        if line == "":
            if "data" in frame:
                yield frame.get("event"), json.loads(frame["data"])
            frame = {}
        elif not line.startswith(":"):  # ":" lines are keep-alives
            field, _, value = line.partition(":")
            frame[field] = value[1:] if value.startswith(" ") else value


def history(client, session_id, since):
    cursor = None
    while True:
        params = {"since": since, "limit": 100} | ({"cursor": cursor} if cursor else {})
        page = client.get(f"{API}/sessions/{session_id}/events", params=params).json()
        yield from page["items"]
        cursor = page["meta"]["next_cursor"]
        if cursor is None:
            return


def follow(client, session_id, since):
    """The session's events after `since`, deltas included, in order, for as long as asked."""
    last = since
    while True:
        try:
            with client.stream(
                "GET",
                f"{API}/sessions/{session_id}/events/stream",
                params={"since": last},
                timeout=None,
            ) as response:
                response.raise_for_status()
                for event, data in sse_events(response):
                    seq = data.get("seq")
                    if seq is None:  # a delta
                        yield event, data
                        continue
                    if seq > last + 1:  # the stream skipped some: read them from the history
                        for missed in history(client, session_id, last):
                            last = missed["seq"]
                            yield missed["type"], missed
                    if seq > last:
                        last = seq
                        yield event, data
        except httpx.TransportError:
            continue  # reconnect from `last`


# ---------------------------------------------------------------------------
# One turn: send the message, print the answer, run the custom tools it calls.
# ---------------------------------------------------------------------------


def ask(client, session_id, content):
    sent = client.post(f"{API}/sessions/{session_id}/messages", json={"content": content})
    sent.raise_for_status()
    message = sent.json()
    calls = {}  # tool_use_id -> agent.custom_tool_use
    for event, data in follow(client, session_id, since=message["seq"]):
        if data["turn_id"] != message["turn_id"]:
            continue
        if event == "agent.message.delta":
            print(data["content"], end="", flush=True)
        elif event == "agent.message" and not data["content"]:
            print("\n[the reply above was withdrawn; regenerating]")  # the deltas were discarded
        elif event == "agent.tool_use":
            print(f"\n[{data['name']}]", flush=True)
        elif event == "agent.custom_tool_use":
            calls[data["id"]] = data
        elif event == "turn.requires_action":  # not the end: answer, and the turn goes on
            results = [run_tool(calls[action["tool_use_id"]]) for action in data["required_actions"]]
            client.post(
                f"{API}/sessions/{session_id}/events",
                json={"events": results},
                headers={"Idempotency-Key": str(uuid.uuid4())},  # a retry reuses this key
            ).raise_for_status()
        elif event in TERMINAL:
            print(f"\n({event}: {data.get('stop_reason') or data.get('error_code') or 'cancelled'})")
            return data


def main():
    with httpx.Client(headers=HEADERS, timeout=60) as client:
        created = client.post(
            f"{API}/sessions",
            json={
                "model_id": MODEL,
                "instruction": "You are a shop's support agent. Use the tools for anything "
                "about an order; never guess an order's state.",
                "custom_tools": CUSTOM_TOOLS,
            },
        )
        created.raise_for_status()
        session_id = created.json()["id"]
        print(f"session {session_id}")
        try:
            if len(sys.argv) > 1:
                ask(client, session_id, " ".join(sys.argv[1:]))
                return
            while content := input("\n> ").strip():
                ask(client, session_id, content)
        except KeyboardInterrupt:
            # Stop whatever is queued, running or waiting, then let the session go.
            client.post(f"{API}/sessions/{session_id}/cancel")
            print("\ncancelled")


if __name__ == "__main__":
    main()
