"""Larkfield's pricing functions as a small stdio MCP server. Chio owns the public HTTP edge."""
from decimal import ROUND_HALF_UP, Decimal
import json
from pathlib import Path
import sys
import uuid

PRICES = {"sku-118": Decimal("24.00"), "sku-204": Decimal("58.00"), "sku-301": Decimal("140.00")}
CENT = Decimal("0.01")
directory = Path("state/mcp/quotes")
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
schema = {"type": "object", "properties": {"sku": {"type": "string"}, "percent": {"type": "number"}}, "required": ["sku", "percent"]}
tools = [
    {"name": "quote", "description": "Quote a SKU at a discount, rounded half up to the cent, and record the quote", "inputSchema": schema},
    {"name": "discount", "description": "Apply a discount to a SKU's list price without rounding", "inputSchema": schema, "annotations": {"readOnlyHint": True}},
]


def discounted(arguments):
    sku, percent = arguments["sku"], arguments["percent"]
    if sku not in PRICES:
        raise ValueError(f"unknown sku {sku}")
    if not isinstance(percent, (int, float)) or not 0 <= percent <= 100:
        raise ValueError("percent must be between 0 and 100")
    return sku, percent, PRICES[sku] * (1 - Decimal(str(percent)) / 100)


for line in sys.stdin:
    request = {}
    try:
        request = json.loads(line)
        if "id" not in request:
            continue
        method = request["method"]
        if method == "initialize":
            result = {"protocolVersion": request["params"]["protocolVersion"], "capabilities": {"tools": {}}, "serverInfo": {"name": "pricing", "version": "1.0.0"}}
        elif method == "tools/list":
            result = {"tools": tools}
        elif method == "ping":
            result = {}
        elif method == "tools/call":
            params = request["params"]
            sku, percent, price = discounted(params["arguments"])
            if params["name"] == "quote":
                value = {"id": str(uuid.uuid4()), "sku": sku, "percent": percent, "price": str(price.quantize(CENT, ROUND_HALF_UP)), "currency": "USD"}
                with (directory / f"{value['id']}.json").open("x") as target:
                    json.dump(value, target)
            elif params["name"] == "discount":
                value = {"sku": sku, "percent": percent, "price": str(price), "currency": "USD"}
            else:
                raise ValueError("Unknown tool")
            result = {"content": [{"type": "text", "text": json.dumps(value)}], "isError": False}
        else:
            raise ValueError("Unsupported method")
        response = {"jsonrpc": "2.0", "id": request["id"], "result": result}
    except (ValueError, KeyError, OSError) as error:
        response = {"jsonrpc": "2.0", "id": request.get("id"), "error": {"code": -32602, "message": str(error)}}
    print(json.dumps(response), flush=True)
