"""Original constructed monitoring cases; not a calibrated detector or fairness/privacy guarantee."""
import json


def make_batch(scores=(.2, .4, .6, .8), change_b_labels=False, labels_available=True):
    rows = []
    for group in ("A", "B"):
        for _ in range(5):
            for i, score in enumerate(scores):
                label = int(i >= 2)
                if change_b_labels and group == "B":
                    label = 0
                rows.append({"group": group, "score": score,
                             "label": label if labels_available else None})
    return rows


def distribution(rows):
    # Fixed, left-closed bins [0,.25), [.25,.5), [.5,.75), [.75,1].
    counts = [0, 0, 0, 0]
    for row in rows:
        score = row["score"]
        if not 0 <= score <= 1:
            raise ValueError("Score outside [0,1]")
        counts[min(int(score * 4), 3)] += 1
    return {"counts": counts, "proportions": [n / len(rows) for n in counts]}


def labeled_metrics(rows):
    known = [r for r in rows if r["label"] is not None]
    if not known:
        return {"total": len(rows), "labeled": 0, "accuracy": None,
                "confusion": None, "TPR": None, "FPR": None}
    tp = sum(r["label"] == 1 and r["score"] >= .5 for r in known)
    fp = sum(r["label"] == 0 and r["score"] >= .5 for r in known)
    tn = sum(r["label"] == 0 and r["score"] < .5 for r in known)
    fn = sum(r["label"] == 1 and r["score"] < .5 for r in known)
    return {"total": len(rows), "labeled": len(known), "accuracy": (tp + tn) / len(known),
            "confusion": {"TP": tp, "FP": fp, "TN": tn, "FN": fn},
            "TPR": tp / (tp + fn) if tp + fn else None,
            "FPR": fp / (fp + tn) if fp + tn else None}


def describe(rows, reference_distribution):
    actual = distribution(rows)
    tv = .5 * sum(abs(a - b) for a, b in zip(actual["proportions"], reference_distribution["proportions"]))
    return {"score_distribution": actual, "score_histogram_total_variation": tv,
            "handset_threshold": .2, "histogram_alert": tv > .2,
            "all": labeled_metrics(rows),
            "groups": {g: labeled_metrics([r for r in rows if r["group"] == g]) for g in ("A", "B")}}


def main():
    reference = make_batch()
    reference_distribution = distribution(reference)
    cases = {"reference": describe(reference, reference_distribution),
        "same_scores_changed_B_labels": describe(make_batch(change_b_labels=True), reference_distribution),
        "shifted_scores_same_correct_decisions": describe(make_batch(scores=(.05, .1, .9, .95)), reference_distribution),
        "same_scores_labels_delayed": describe(make_batch(change_b_labels=True, labels_available=False), reference_distribution)}
    assert cases["reference"]["all"]["accuracy"] == 1
    changed = cases["same_scores_changed_B_labels"]
    assert changed["score_histogram_total_variation"] == 0 and not changed["histogram_alert"]
    assert changed["all"]["accuracy"] == .75
    assert changed["groups"]["A"]["accuracy"] == 1 and changed["groups"]["B"]["accuracy"] == .5
    assert changed["groups"]["B"]["TPR"] is None and changed["groups"]["B"]["FPR"] == .5
    shifted = cases["shifted_scores_same_correct_decisions"]
    assert shifted["score_histogram_total_variation"] == .5 and shifted["histogram_alert"]
    assert shifted["all"]["accuracy"] == 1
    assert cases["same_scores_labels_delayed"]["all"]["accuracy"] is None
    print(json.dumps({"scope": "Four constructed 40-row batches, fixed score threshold .5, no model training or live monitor",
        "cases": cases,
        "limits": ["Histogram drift is score-distribution drift only, not all raw features or all concept changes.",
            "Threshold .2 is hand chosen, not calibrated for sampling noise, false alarms or multiple tests.",
            "Labels are changed by construction; real shifts require investigation and trustworthy feedback.",
            "A/B are synthetic cohorts, not actual protected demographics or proof of fairness/unfairness.",
            "Undefined rates are null, not zero; missing labels do not authorize reporting accuracy.",
            "Aggregate counts alone do not establish anonymity, privacy compliance or differential privacy.",
            "No latency/load, alert service, privacy audit or production outcome was measured."]}, indent=2, allow_nan=False))


if __name__ == "__main__":
    main()
