"""اعتبارسنجی خروجی JSON مدل با Schema — درس FND-102-L05.
نصب: pip install jsonschema
اجرا: python validate_output.py outputs.jsonl
هر خط outputs.jsonl یک خروجی مدل است (متن خام). اسکریپت سه سطح خطا را جدا گزارش می‌کند:
JSON نامعتبر، نقض Schema، و نقض قاعده معنایی (شماره سفارشی که در پیام نیست).
"""
import json
import sys

from jsonschema import Draft202012Validator

schema = json.load(open("ticket-schema.json", encoding="utf-8"))
validator = Draft202012Validator(schema)

for n, line in enumerate(open(sys.argv[1], encoding="utf-8"), 1):
    record = json.loads(line)  # {"message": "...", "output": "<متن خام مدل>"}
    try:
        data = json.loads(record["output"])
    except json.JSONDecodeError as e:
        print(f"{n}: INVALID_JSON {e}")
        continue
    errors = [e.message for e in validator.iter_errors(data)]
    if errors:
        print(f"{n}: SCHEMA {errors}")
        continue
    if data["order_id"] and data["order_id"] not in record["message"]:
        print(f"{n}: SEMANTIC order_id {data['order_id']} not in message")
        continue
    print(f"{n}: OK {data['category']}")
