"""Runnable MCP example: estimate and save a declaration with the ``estimate_entry`` tool.

TARIFFTRUST_URL=https://api.tarifftrust.com TARIFFTRUST_API_KEY=tarifftrust_... python mcp_entry.py
"""

import json
import os
import sys

import httpx


def call(url, key, method, params=None, identifier=1):
    response = httpx.post(
        url.rstrip("/") + "/mcp/",
        json={"jsonrpc": "2.0", "id": identifier, "method": method, "params": params or {}},
        headers={"Authorization": f"Bearer {key}"},
        timeout=30,
    )
    response.raise_for_status()
    message = response.json()
    if "error" in message:
        raise RuntimeError(message["error"]["message"])
    return message["result"]


def main(url=None, key=None):
    url, key = url or os.environ["TARIFFTRUST_URL"], key or os.environ["TARIFFTRUST_API_KEY"]
    call(url, key, "initialize", {"protocolVersion": "2025-11-25"})
    tools = [tool["name"] for tool in call(url, key, "tools/list", identifier=2)["tools"]]
    result = call(
        url,
        key,
        "tools/call",
        {
            "name": "estimate_entry",
            "arguments": {
                "lines": [
                    {"hts": "6109.10.00.12", "origin": "CN", "customs_value": "1000"},
                    {"hts": "6109.10.00.12", "origin": "VN", "customs_value": "2500"},
                ],
                "facts": {},
                "save": True,
            },
        },
        identifier=3,
    )["structuredContent"]
    print(
        json.dumps({"tools": tools, "status": result["status"], "calculation_id": result["calculation_id"]})
    )
    return result


if __name__ == "__main__":
    main()
    sys.exit(0)
