#!/usr/bin/env python3
"""
sentiqra-compare — customer-local configuration comparison.

Runs YOUR evaluation set against two pinned configurations (old vs new)
and reports what actually changes for your integration: added/removed
signal codes, score movements, and — with a policy map — changed
downstream actions.

This is how you answer "does upgrading my pinned configuration change my
policy behavior?" BEFORE moving the pin. A pin is never moved for you;
there is no automatic migration.

YOUR DATA NEVER LEAVES YOUR ENVIRONMENT. The only network calls are the
same POST /v1/analyze requests your production traffic already makes —
with detection_config set to each pin. The dataset, the policy map, and
the report stay on your machine. The API does not retain evaluation
text; the report itself omits it (row references only) so it is safe to
attach to a support ticket.

Usage:
    export SENTIQRA_API_KEY=sq_live_...
    python3 sentiqra-compare.py --dataset eval.jsonl --old <current-pin> --new <candidate-pin>
    python3 sentiqra-compare.py --dataset eval.jsonl --old ... --new ... --policy policy.json --out diff.json

Dataset format (JSONL, one object per line):
    {"text": "...", "language": "en", "domain": "trust-safety"}
    {"text": "...", "language": "en", "domain": "fraud-scam", "id": "case-42"}

Policy map (optional JSON):
    {"version": "policy_v3",
     "actions": {"threats_intimidation": "block", "spam_platform_abuse": "review"},
     "default": "allow"}
    Keys match signal codes (and parent group codes); an input's action set is
    the union of actions its signals trigger, or {"default"} value.

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

import argparse
import json
import sys
import time
import urllib.request
import urllib.error
from getpass import getpass
from os import environ

PIN_RE = __import__("re").compile(r"^sqcfg_[0-9A-HJKMNP-TV-Z]{8}$")


def analyze(base, key, domain, text, language, pin, timeout=30):
    body = json.dumps({
        "text": text,
        "language": language,
        "analyzers": [domain],
        "detection_config": pin,
    }).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 signal_set(resp):
    """{(parent group, code): score} — the customer-visible signal identity.
    Category rows carry no parent; their code IS the group."""
    out = {}
    for s in resp.get("signals", []) or []:
        ident = (s.get("parent"), s.get("code"))
        score = s.get("score", s.get("confidence"))
        out[ident] = score
    return out


def actions_for(sigset, policy):
    if not policy:
        return None
    acts = policy.get("actions", {})
    hits = set()
    for gtype, code in sigset:
        for key in (code, gtype):
            if key and key in acts:
                hits.add(acts[key])
    return hits or {policy.get("default", "allow")}


def main():
    ap = argparse.ArgumentParser(
        description="Compare two pinned configurations on your own data — local only")
    ap.add_argument("--dataset", required=True, help="JSONL eval set (stays local)")
    ap.add_argument("--old", required=True, help="current pinned configuration alias")
    ap.add_argument("--new", required=True, help="candidate configuration alias")
    ap.add_argument("--policy", default=None, help="JSON policy map (code/type -> action)")
    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 diff report to this path")
    ap.add_argument("--delay", type=float, default=1.05, help="Seconds between calls")
    ap.add_argument("--limit", type=int, default=0, help="Cap items (smoke test)")
    args = ap.parse_args()

    for pin in (args.old, args.new):
        if not PIN_RE.match(pin):
            sys.exit(f"{pin}: not a configuration alias (sqcfg_ + 8 chars)")

    policy = None
    if args.policy:
        policy = json.load(open(args.policy, encoding="utf-8"))

    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"):
                if field not in row:
                    sys.exit(f"line {i}: missing required field '{field}'")
            row.setdefault("language", "en")
            items.append(row)
    if args.limit:
        items = items[: args.limit]
    if not items:
        sys.exit("dataset is empty")

    diffs = []
    errors = 0
    for i, item in enumerate(items):
        row_diff = {"row": i, "id": item.get("id"), "domain": item["domain"]}
        try:
            old = signal_set(analyze(base, key, item["domain"], item["text"], item["language"], args.old))
            new = signal_set(analyze(base, key, item["domain"], item["text"], item["language"], args.new))
        except urllib.error.HTTPError as e:
            body = e.read().decode()[:200]
            sys.exit(f"item {i}: HTTP {e.code} — {body}\n"
                     "Check both pins are valid for this analyzer set and within their support window.")
        except (urllib.error.URLError, TimeoutError, OSError) as e:
            errors += 1
            print(f"  item {i}: request error ({e}) — skipped", file=sys.stderr)
            time.sleep(args.delay)
            continue

        added = [f"{t}/{c}" if c else t for (t, c) in sorted(set(new) - set(old))]
        removed = [f"{t}/{c}" if c else t for (t, c) in sorted(set(old) - set(new))]
        moved = [
            {"signal": f"{t}/{c}" if c else t, "old": old[(t, c)], "new": new[(t, c)]}
            for (t, c) in sorted(set(old) & set(new)) if old[(t, c)] != new[(t, c)]
        ]
        old_act = actions_for(old, policy)
        new_act = actions_for(new, policy)
        if added or removed or moved or (old_act is not None and old_act != new_act):
            row_diff.update({"added": added, "removed": removed, "score_changes": moved})
            if old_act is not None:
                row_diff["actions_old"] = sorted(old_act)
                row_diff["actions_new"] = sorted(new_act)
                row_diff["action_changed"] = old_act != new_act
            diffs.append(row_diff)
        if i % 20 == 0:
            print(f"  {i}/{len(items)}", file=sys.stderr)
        time.sleep(args.delay)

    changed_actions = sum(1 for d in diffs if d.get("action_changed"))
    report = {
        "tool": "sentiqra-compare/1",
        "old_configuration": args.old,
        "new_configuration": args.new,
        "policy_version": (policy or {}).get("version"),
        "evaluated": len(items) - errors,
        "errors": errors,
        "rows_changed": len(diffs),
        "actions_changed": changed_actions if policy else None,
        "diffs": diffs,  # row references only — no evaluation text
    }

    print(f"\n{len(items) - errors} inputs compared "
          f"({args.old} → {args.new})")
    print(f"  rows with signal changes: {len(diffs)}")
    if policy:
        print(f"  rows with changed downstream actions: {changed_actions}")
    if errors:
        print(f"  request errors (skipped): {errors}", file=sys.stderr)
    for d in diffs[:20]:
        print(f"  row {d['row']} ({d['domain']}): "
              f"+{len(d.get('added', []))} -{len(d.get('removed', []))} "
              f"~{len(d.get('score_changes', []))}"
              + (f" actions {d['actions_old']}→{d['actions_new']}" if d.get("action_changed") else ""))
    if len(diffs) > 20:
        print(f"  … and {len(diffs) - 20} more (see --out 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)

    # Non-zero exit when a pin move would change behavior — usable in CI
    # as a pre-adoption check.
    sys.exit(1 if diffs else 0)


if __name__ == "__main__":
    main()
