import json
import os
from jsonschema import Draft202012Validator
from openai import OpenAI


SCHEMA = {"type": "object", "properties": {
    "order_id": {"type": "string"}, "quantity": {"type": "integer"},
    "delivery_date": {"type": ["string", "null"]}},
    "required": ["order_id", "quantity", "delivery_date"], "additionalProperties": False}


def validate_record(record):
    Draft202012Validator(SCHEMA).validate(record)
    if record["quantity"] < 0:
        raise ValueError("quantity must not be negative")
    return record


def main():
    client = OpenAI(api_key=os.environ["QUICKROUTER_API_KEY"],
                    base_url="https://api.quickrouter.ai/v1", timeout=60, max_retries=0)
    response = client.chat.completions.create(
        model=os.environ["QUICKROUTER_MODEL"],
        messages=[{"role": "user", "content": "提取订单：订单号 QR-101，数量 3，未约定交付日期。未知日期填 null。"}],
        response_format={"type": "json_schema", "json_schema": {
            "name": "order", "strict": True, "schema": SCHEMA}})
    if not response.choices:
        raise RuntimeError("Empty choices; preserve the response before retrying")
    choice = response.choices[0]
    if getattr(choice.message, "refusal", None):
        raise RuntimeError("Model refused; do not treat this as an order")
    if choice.finish_reason != "stop" or not choice.message.content:
        raise RuntimeError("Incomplete output; do not parse a partial JSON record")
    record = validate_record(json.loads(choice.message.content))
    if record != {"order_id": "QR-101", "quantity": 3, "delivery_date": None}:
        raise RuntimeError("Schema passed but source facts did not match")
    print(json.dumps(record, ensure_ascii=False))
    print("usage:", response.usage)


if __name__ == "__main__":
    main()
