#!/usr/bin/env python3
"""
sentiqra-eval — local decision-quality evaluation for the Sentiqra API.

Runs your own labeled dataset against the analyzers you use and computes
the same published metrics: a defined false-positive measure, abstention
and coverage, per-label precision/recall, and policy errors at stated
operating points — all with Wilson 95% intervals.

YOUR DATA NEVER LEAVES YOUR ENVIRONMENT. The only network calls are the
same POST /v1/analyze requests your production traffic already makes;
the labeled dataset file is read locally and is never transmitted.

Usage:
    export SENTIQRA_API_KEY=sq_live_...
    python3 sentiqra-eval.py --dataset eval.jsonl
    python3 sentiqra-eval.py --dataset eval.jsonl --base https://sentiqra.tech --out report.json

Optional aggregate reporting (helps Sentiqra investigate a quality issue
without ever seeing your data):
    python3 sentiqra-eval.py --dataset eval.jsonl --submit
    python3 sentiqra-eval.py --dataset eval.jsonl --submit-dry-run   # print payload, send nothing

--submit POSTs a fixed-schema aggregate (counts, rates, public
configuration aliases) to POST /v1/eval-report. The payload contains no
case text, no per-item rows, and no dataset content — the server
enforces the same allowlist and rejects content-bearing fields.

Dataset format (JSONL, one object per line):
    {"text": "...", "language": "en", "domain": "trust-safety", "label": "death_threat"}
    {"text": "...", "language": "en", "domain": "trust-safety", "label": "negative"}

Label semantics:
    "negative"  — your expectation is NO signal; any emitted signal is a
                  false positive under your labeling policy.
    <code>      — positive item; hit = that code appears in the signals.
    "boundary"  — ambiguous item; flag rate is reported but never judged.

Requires: Python 3.8+, no third-party packages.
"""

import argparse
import hashlib
import json
import math
import sys
import time
import urllib.request
import urllib.error
from collections import defaultdict
from getpass import getpass
from os import environ

OPERATING_POINTS = [0.70, 0.80, 0.90, 0.95]
MIN_SUPPORT = 5
Z = 1.959963984540054  # 95% Wilson


def wilson(k, n):
    """Wilson score interval -> (rate, lo, hi); (None, None, None) if n==0."""
    if n <= 0:
        return None, None, None
    p = k / n
    denom = 1 + Z * Z / n
    center = (p + Z * Z / (2 * n)) / denom
    adj = Z * math.sqrt(p * (1 - p) / n + Z * Z / (4 * n * n)) / denom
    return round(p, 4), round(max(0.0, center - adj), 4), round(min(1.0, center + adj), 4)


def analyze(base, key, domain, text, language, timeout=30):
    body = json.dumps({
        "text": text,
        "language": language,
        "analyzers": [domain],
    }).encode()
    req = urllib.request.Request(
        f"{base}/v1/analyze", data=body, method="POST",
        headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=timeout) as res:
        return json.loads(res.read())


def main():
    ap = argparse.ArgumentParser(description="Local decision-quality eval for the Sentiqra API")
    ap.add_argument("--dataset", required=True, help="JSONL labeled dataset (stays local)")
    ap.add_argument("--base", default="https://sentiqra.tech", help="API base URL (no /v1 suffix)")
    ap.add_argument("--api-key", default=environ.get("SENTIQRA_API_KEY"),
                    help="API key (default: $SENTIQRA_API_KEY; prompted if unset)")
    ap.add_argument("--out", default=None, help="Write JSON report to this path")
    ap.add_argument("--delay", type=float, default=1.05, help="Seconds between calls (default 1.05)")
    ap.add_argument("--limit", type=int, default=0, help="Cap items (smoke test)")
    ap.add_argument("--submit", action="store_true",
                    help="POST the aggregate-only report to POST /v1/eval-report on the portal")
    ap.add_argument("--submit-dry-run", action="store_true",
                    help="Print the exact aggregate payload --submit would send; sends nothing")
    ap.add_argument("--portal", default="https://sentiqra.tech",
                    help="Portal base URL for --submit (default https://sentiqra.tech)")
    args = ap.parse_args()

    key = args.api_key or getpass("SENTIQRA_API_KEY: ")
    base = args.base.rstrip("/")

    items = []
    with open(args.dataset, encoding="utf-8") as fh:
        for i, line in enumerate(fh, 1):
            line = line.strip()
            if not line:
                continue
            try:
                row = json.loads(line)
            except json.JSONDecodeError as e:
                sys.exit(f"line {i}: invalid JSON: {e}")
            for field in ("text", "domain", "label"):
                if field not in row:
                    sys.exit(f"line {i}: missing required field '{field}'")
            row.setdefault("language", "en")
            row.setdefault("category", "unlabeled")
            items.append(row)
    if args.limit:
        items = items[: args.limit]
    if not items:
        sys.exit("dataset is empty")

    results = []
    errors = 0
    configs_seen = set()
    for i, item in enumerate(items):
        r = {"label": item["label"], "domain": item["domain"],
             "category": item["category"], "language": item["language"],
             "predicted": [], "abstained": True, "error": False}
        try:
            resp = analyze(base, key, item["domain"], item["text"], item["language"])
            r["predicted"] = [
                {"code": s["code"], "score": float(s.get("score") or 0)}
                for s in resp.get("signals", []) if s.get("code")
            ]
            r["abstained"] = not r["predicted"]
            cfg = (resp.get("verification") or {}).get("configuration")
            if isinstance(cfg, str) and cfg.startswith("sqcfg_"):
                configs_seen.add(cfg)
        except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError) as e:
            r["error"] = True
            errors += 1
            print(f"  item {i}: eval error ({e}) — counted as miss, not dropped", file=sys.stderr)
        results.append(r)
        if i % 25 == 0:
            print(f"  {i}/{len(items)}", file=sys.stderr)
        time.sleep(args.delay)

    report = build_report(results, errors)
    print_report(report)

    if args.out:
        with open(args.out, "w", encoding="utf-8") as fh:
            json.dump(report, fh, indent=2)
        print(f"\nreport → {args.out}", file=sys.stderr)

    if args.submit_dry_run or args.submit:
        payload = aggregate_payload(report, args.dataset, configs_seen)
        if args.submit_dry_run:
            print("\nsubmission payload (dry run — nothing sent):", file=sys.stderr)
            print(json.dumps(payload, indent=2))
        else:
            submit_aggregate(args.portal.rstrip("/"), key, payload)


def aggregate_payload(report, dataset_path, configs_seen):
    """Build the approved-aggregate payload for POST /v1/eval-report.

    Counts and rates only — per-domain rollups. No case text, no
    per-item rows, no customer-defined bucket/category strings: the
    schema is the approval boundary and the server rejects anything
    outside it.
    """
    domains = {}
    for bk, b in report.get("buckets", {}).items():
        domain = bk.split("|", 1)[0]
        d = domains.setdefault(domain, {"items": 0, "flagged": 0, "negatives": 0,
                                        "negatives_flagged": 0, "positives": 0, "hits": 0})
        d["items"] += b["n"]
        d["flagged"] += (b["flag"] or {}).get("k", 0) or 0
        d["negatives"] += (b["fp"] or {}).get("n", 0) or 0
        d["negatives_flagged"] += (b["fp"] or {}).get("k", 0) or 0
        d["positives"] += (b["hit"] or {}).get("n", 0) or 0
        d["hits"] += (b["hit"] or {}).get("k", 0) or 0
    for d in domains.values():
        d["flag_rate"] = round(d["flagged"] / d["items"], 4) if d["items"] else None
        d["fp_rate"] = round(d["negatives_flagged"] / d["negatives"], 4) if d["negatives"] else None
        d["hit_rate"] = round(d["hits"] / d["positives"], 4) if d["positives"] else None

    return {
        "schema": "sentiqra/eval-aggregate/v1",
        "tool": {"name": "sentiqra-eval", "version": "1.1"},
        "eval_set": {
            "name": dataset_path.rsplit("/", 1)[-1][:120],
            "sha256": hashlib.sha256(open(dataset_path, "rb").read()).hexdigest(),
            "items": report["items"],
        },
        "configurations": sorted(configs_seen),
        "aggregates": {
            "items": report["items"],
            "eval_errors": report["eval_errors"],
            "fp_measure": report["fp_measure"],
            "hit_measure": report["hit_measure"],
            "abstention": report["abstention"],
            "domains": domains,
        },
    }


def submit_aggregate(portal, key, payload):
    body = json.dumps(payload).encode()
    req = urllib.request.Request(
        f"{portal}/v1/eval-report", data=body, method="POST",
        headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=30) as res:
            out = json.loads(res.read())
    except urllib.error.HTTPError as e:
        sys.exit(f"aggregate submission rejected ({e.code}): {e.read().decode()[:300]}")
    except (urllib.error.URLError, TimeoutError, OSError) as e:
        sys.exit(f"aggregate submission failed: {e}")
    print(f"\naggregate report received: {out.get('report_id')}", file=sys.stderr)


def build_report(results, errors):
    buckets = defaultdict(lambda: {"n": 0, "flags": 0, "abstained": 0,
                                   "n_neg": 0, "fp": 0, "n_pos": 0, "hits": 0})
    labels = defaultdict(lambda: {"support": 0, "tp": 0, "fp": 0})
    fp_n = fp_k = 0
    pos_n = pos_k = 0
    abst_n = 0
    ops = {str(t): {"n": 0, "covered": 0, "n_neg": 0, "fp": 0, "n_pos": 0, "fn": 0}
           for t in OPERATING_POINTS}

    for r in results:
        codes = {p["code"] for p in r["predicted"]}
        flagged = bool(codes)
        abst_n += r["abstained"]
        label = r["label"]
        negative = label == "negative"
        boundary = label == "boundary"
        positive = not negative and not boundary

        bk = f'{r["domain"]}|{r["category"]}|{r["language"]}'
        b = buckets[bk]
        b["n"] += 1
        b["flags"] += flagged
        b["abstained"] += r["abstained"]
        if negative:
            b["n_neg"] += 1
            b["fp"] += flagged
            fp_n += 1
            fp_k += flagged
        if positive:
            b["n_pos"] += 1
            hit = label in codes
            b["hits"] += hit
            pos_n += 1
            pos_k += hit
            lk = f'{r["domain"]}|{label}'
            labels[lk]["support"] += 1
            labels[lk]["tp"] += hit
            for c in codes - {label}:
                labels[f'{r["domain"]}|{c}']["fp"] += 1
        if negative or boundary:
            for c in codes:
                labels[f'{r["domain"]}|{c}']["fp"] += 1

        for t in OPERATING_POINTS:
            key = str(t)
            action = any(p["score"] >= t for p in r["predicted"])
            expected_hit = positive and any(
                p["score"] >= t and p["code"] == label for p in r["predicted"])
            o = ops[key]
            o["n"] += 1
            o["covered"] += action
            if negative:
                o["n_neg"] += 1
                o["fp"] += action
            if positive:
                o["n_pos"] += 1
                o["fn"] += not expected_hit

    def cell(k, n):
        rate, lo, hi = wilson(k, n)
        return {"n": n, "k": k, "rate": rate, "ci95": [lo, hi]}

    return {
        "report": "sentiqra-local-eval",
        "items": len(results),
        "eval_errors": errors,
        "definitions": {
            "fp_measure": "flag rate over items labeled 'negative' — any emitted signal counts",
            "abstention": "responses emitting zero signals; coverage = 1 - abstention",
            "hit": "positive item whose expected label code was emitted",
            "intervals": "Wilson score intervals at 95%",
            "operating_points": "example decision points, not recommendations",
        },
        "fp_measure": cell(fp_k, fp_n),
        "hit_measure": cell(pos_k, pos_n),
        "abstention": cell(abst_n, len(results)),
        "operating_points": {
            t: {"coverage": cell(o["covered"], o["n"]),
                "policy_fp": cell(o["fp"], o["n_neg"]),
                "policy_miss": cell(o["fn"], o["n_pos"])}
            for t, o in ops.items()},
        "buckets": {
            k: {"n": b["n"], "flag": cell(b["flags"], b["n"]),
                "fp": cell(b["fp"], b["n_neg"]) if b["n_neg"] else None,
                "hit": cell(b["hits"], b["n_pos"]) if b["n_pos"] else None,
                "abstention": cell(b["abstained"], b["n"])}
            for k, b in sorted(buckets.items())},
        "labels": {
            k: {"support": l["support"], "tp": l["tp"], "fp": l["fp"],
                "precision": cell(l["tp"], l["tp"] + l["fp"]),
                "recall": cell(l["tp"], l["support"]),
                "sufficient": l["support"] >= MIN_SUPPORT}
            for k, l in sorted(labels.items())},
    }


def pct(v):
    return "—" if v is None else f"{v * 100:.1f}%"


def ci(c):
    return "" if not c or c["rate"] is None else f"{pct(c['rate'])} [{pct(c['ci95'][0])}–{pct(c['ci95'][1])}] n={c['n']}"


def print_report(r):
    print("\n=== Sentiqra local eval ===")
    print(f"items: {r['items']}  eval errors (counted, not dropped): {r['eval_errors']}")
    print(f"FP measure (no-signal items): {ci(r['fp_measure'])}")
    print(f"Hit measure (positive items): {ci(r['hit_measure'])}")
    print(f"Abstention: {ci(r['abstention'])}")
    print("\nper bucket (domain|category|lang):")
    for k, b in r["buckets"].items():
        print(f"  {k:48s} n={b['n']:4d} flag={ci(b['flag'])} fp={ci(b['fp'])} hit={ci(b['hit'])}")
    print("\nper label (support >= %d shown, others marked insufficient):" % MIN_SUPPORT)
    for k, l in r["labels"].items():
        mark = "" if l["sufficient"] else "  (insufficient support)"
        print(f"  {k:48s} support={l['support']:3d} P={ci(l['precision'])} R={ci(l['recall'])}{mark}")
    print("\noperating points (example decision points — not recommendations):")
    for t, o in r["operating_points"].items():
        print(f"  >= {t}: coverage={ci(o['coverage'])}  policy-FP={ci(o['policy_fp'])}  policy-miss={ci(o['policy_miss'])}")


if __name__ == "__main__":
    main()
