"""Synthetic contract evaluation. Default: dry run. --run makes billable requests."""
import argparse
import json
import os
from pathlib import Path
from time import monotonic

SYSTEM = (
    'از متن فقط JSON با کلیدهای order_id و amount و currency بساز. '
    'شناسه رشته یا null است؛ مبلغ عدد صحیح نامنفی یا null است. '
    'واحد تومان IRT و ریال IRR است. مبلغ را تبدیل نکن. '
    'اگر مبلغ یا واحد نامشخص بود، هر دو را null بگذار. '
    'اطلاعات را حدس نزن و متن اضافه ننویس.'
)


def score_prediction(text, expected):
    try:
        value = json.loads(text)
    except (json.JSONDecodeError, TypeError):
        return False
    if not isinstance(value, dict) or set(value) != {"order_id", "amount", "currency"}:
        return False
    if value["order_id"] is not None and not isinstance(value["order_id"], str):
        return False
    amount, currency = value["amount"], value["currency"]
    if amount is not None and (type(amount) is not int or amount < 0):
        return False
    if currency is not None and currency not in ("IRR", "IRT"):
        return False
    if (amount is None) != (currency is None):
        return False
    return value == expected


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--model", required=True)
    parser.add_argument("--limit", type=int, default=3)
    parser.add_argument("--run", action="store_true")
    args = parser.parse_args()
    if not 1 <= args.limit <= 12 or not args.model or len(args.model) > 160:
        parser.error("Use a model ID and a limit from 1 to 12")
    source = Path(__file__).with_name("persian-eval-cases.jsonl")
    if source.stat().st_size > 100_000:
        raise ValueError("case_file_too_large")
    cases = [json.loads(line) for line in source.read_text(encoding="utf-8").splitlines() if line.strip()]
    if not cases or len(cases) > 12 or len({case["id"] for case in cases}) != len(cases):
        raise ValueError("invalid_cases")
    cases = cases[:args.limit]
    for case in cases:
        if not isinstance(case["text"], str) or len(case["text"]) > 2000:
            raise ValueError("invalid_case_text")
    if not args.run:
        print(json.dumps({"mode": "dry-run", "model": args.model,
                          "cases": [case["id"] for case in cases],
                          "billable_calls": 0}, ensure_ascii=False))
        return
    from openai import OpenAI
    client = OpenAI(api_key=os.environ["PAASTA_AI_KEY"],
                    base_url="https://console.paasta.cloud/api/ai/v1",
                    timeout=45.0, max_retries=0)
    if args.model not in {item.id for item in client.models.list().data}:
        raise SystemExit("model_not_available_for_key")
    results = []
    for case in cases:
        start = monotonic()
        try:
            response = client.chat.completions.create(
                model=args.model,
                messages=[{"role": "system", "content": SYSTEM},
                          {"role": "user", "content": case["text"]}],
                max_tokens=256,
            )
            text = response.choices[0].message.content
            usage = response.usage
            results.append({"case": case["id"], "ok": response.choices[0].finish_reason == "stop" and score_prediction(text, case["expected"]),
                            "duration_ms": round((monotonic() - start) * 1000),
                            "finish_reason": response.choices[0].finish_reason,
                            "input_tokens": getattr(usage, "prompt_tokens", None),
                            "output_tokens": getattr(usage, "completion_tokens", None)})
        except Exception as error:
            results.append({"case": case["id"], "ok": False,
                            "status": "request_failed_or_uncertain",
                            "error_type": type(error).__name__,
                            "duration_ms": round((monotonic() - start) * 1000)})
    print(json.dumps({"model": args.model, "results": results}, ensure_ascii=False))


if __name__ == "__main__":
    main()
