"""Complete OpenAI Agents SDK example for synthetic inquiry routing.

Official Quickstart: Agent + Runner + @tool
(https://openai.github.io/openai-agents-python/quickstart/).

Live `Runner.run` is NOT executed in CI. It needs `openai-agents`,
OPENAI_API_KEY, and separate cost authorization. Offline tests use
the same `policy.mjs` through MCP/Skill adapters instead.
"""

from __future__ import annotations

import asyncio
import json
import subprocess
from pathlib import Path

from agents import Agent, Runner
from agents.decorators import tool

ROOT = Path(__file__).resolve().parent
RUNNER = ROOT / "run-policy.mjs"


def route_synthetic_inquiry(inquiry: dict) -> dict:
    """Same policy as n8n / MCP / Skill. Never sends."""
    completed = subprocess.run(
        ["node", str(RUNNER)],
        input=json.dumps(inquiry),
        check=True,
        capture_output=True,
        text=True,
    )
    return json.loads(completed.stdout)


@tool
def route_synthetic_inquiry_tool(inquiry: dict) -> dict:
    """Validate and route one synthetic inquiry. Review only; never send."""
    return route_synthetic_inquiry(inquiry)


agent = Agent(
    name="Synthetic inquiry reviewer",
    instructions=(
        "You draft review-only routing for SYNTHETIC inquiries. "
        "Always call route_synthetic_inquiry_tool. "
        "Never claim human approval, prices, stock, certification, or that mail was sent. "
        "Repeat requiresHumanReview and sendAllowed from the tool."
    ),
    tools=[route_synthetic_inquiry_tool],
)


async def main() -> None:
    result = await Runner.run(
        agent,
        "Route this synthetic inquiry JSON: "
        '{"id":"DEMO-001","email":"buyer@example.com","language":"en",'
        '"message":"Please quote DEMO-A","quantity":12}',
    )
    print(result.final_output)


if __name__ == "__main__":
    asyncio.run(main())
