"""Keep http-client.py beside this file. pip install requests jsonschema."""
import argparse
import importlib.util
import json
import os
from pathlib import Path

import requests
from jsonschema import Draft202012Validator

SPEC = importlib.util.spec_from_file_location("yunqi_http", Path(__file__).with_name("http-client.py"))
HTTP = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(HTTP)


def validate_schema(schema):
    def check(node):
        if isinstance(node, dict):
            if "$ref" in node and not node["$ref"].startswith("#"):
                raise ValueError("Example accepts only local JSON Schema references")
            for value in node.values():
                check(value)
        elif isinstance(node, list):
            for value in node:
                check(value)
    check(schema)
    Draft202012Validator.check_schema(schema)


def build_request(protocol, model, prompt, schema):
    if protocol == "gemini" or model == "claude-opus-5-5":
        raise ValueError("Native JSON Schema enforcement is not in the current contract for this model/protocol")
    validate_schema(schema)
    route, body = HTTP.build_body(protocol, model, prompt)
    if protocol == "responses":
        body["text"] = {"format": {"type": "json_schema", "name": "customer_result", "strict": True, "schema": schema}}
    elif protocol == "messages":
        body["output_config"] = {"format": {"type": "json_schema", "schema": schema}}
    else:
        body["response_format"] = {"type": "json_schema", "json_schema": {"name": "customer_result", "strict": True, "schema": schema}}
    return route, body


def parse_result(protocol, data, schema):
    text = HTTP.inspect_result(protocol, data)
    result = json.loads(text)
    Draft202012Validator(schema).validate(result)
    return result


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("protocol", choices=["responses", "messages", "chat"])
    parser.add_argument("--schema", required=True)
    parser.add_argument("--prompt", required=True)
    args = parser.parse_args()
    schema = json.loads(Path(args.schema).read_text(encoding="utf-8"))
    key, model = os.environ["YUNQIAI_API_KEY"], os.environ["YUNQIAI_MODEL"]
    route, body = build_request(args.protocol, model, args.prompt, schema)
    headers = {"Authorization": "Bearer " + key}
    if args.protocol == "messages":
        headers = {"x-api-key": key, "anthropic-version": "2023-06-01"}
    response = requests.post("https://www.yunqiai.chat" + route, headers=headers, json=body, allow_redirects=False, timeout=(15, 300))
    if not 200 <= response.status_code < 300:
        raise RuntimeError("HTTP " + str(response.status_code) + ": " + response.text[:4000])
    print(json.dumps(parse_result(args.protocol, response.json(), schema), ensure_ascii=False))


if __name__ == "__main__":
    main()
