"""Original synthetic order-review project: predeclared split, validation choice, one test evaluation."""
import hashlib
import json
import math
import platform
import random

import numpy as np
import sklearn
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler


def metrics(labels, predicted):
    tp = sum(y == 1 and p == 1 for y, p in zip(labels, predicted))
    fp = sum(y == 0 and p == 1 for y, p in zip(labels, predicted))
    tn = sum(y == 0 and p == 0 for y, p in zip(labels, predicted))
    fn = sum(y == 1 and p == 0 for y, p in zip(labels, predicted))
    return {"n": len(labels), "TP": tp, "FP": fp, "TN": tn, "FN": fn,
        "cost_FN5_FP1": 5 * fn + fp,
        "recall": tp / (tp + fn) if tp + fn else None,
        "precision": tp / (tp + fp) if tp + fp else None,
        "review_count": tp + fp, "accuracy": (tp + tn) / len(labels)}


def main():
    # Declared before looking at the held-out test: synthetic teaching costs, not business estimates.
    thresholds = [.1, .2, .3, .4, .5, .6, .7, .8, .9]
    minimum_recall = .8
    rng = random.Random(42)
    records = []
    for row_id in range(300):
        distance = rng.uniform(5, 100)
        queue = rng.randrange(0, 21)
        promised_days = rng.choice([1, 2, 3, 4])
        fragile = rng.randrange(2)
        # All features represent information available at order creation, before the synthetic label.
        logit = -3 + .025 * distance + .16 * queue - .7 * promised_days + .7 * fragile
        label = int(rng.random() < 1 / (1 + math.exp(-logit)))
        records.append({"id": row_id, "features": [distance, queue, promised_days, fragile], "late": label})
    x = np.asarray([r["features"] for r in records], dtype=float)
    y = np.asarray([r["late"] for r in records], dtype=int)
    development, test_ids = train_test_split(np.arange(300), test_size=.2, stratify=y, random_state=17)
    train_ids, validation_ids = train_test_split(development, test_size=.25,
        stratify=y[development], random_state=19)
    assert not set(train_ids) & set(validation_ids) and not set(development) & set(test_ids)
    model = Pipeline([("scale", StandardScaler()),
        ("classifier", LogisticRegression(C=1, max_iter=1000, random_state=0))])
    model.fit(x[train_ids], y[train_ids])
    validation_probability = model.predict_proba(x[validation_ids])[:, 1]
    candidates = [{"threshold": t, **metrics(y[validation_ids].tolist(),
        (validation_probability >= t).astype(int).tolist())} for t in thresholds]
    choice = min(candidates, key=lambda r: (r["cost_FN5_FP1"], -r["threshold"]))
    constant_candidates = [{"constant": c, **metrics(y[validation_ids].tolist(),
        [c] * len(validation_ids))} for c in (0, 1)]
    baseline_choice = min(constant_candidates, key=lambda r: (r["cost_FN5_FP1"], r["constant"]))
    # Freeze the model, threshold and baseline choices. No refit after validation or test.
    test_probability = model.predict_proba(x[test_ids])[:, 1]
    test_prediction = (test_probability >= choice["threshold"]).astype(int).tolist()
    test_result = metrics(y[test_ids].tolist(), test_prediction)
    baseline_test = metrics(y[test_ids].tolist(), [baseline_choice["constant"]] * len(test_ids))
    accepted = (test_result["cost_FN5_FP1"] < baseline_test["cost_FN5_FP1"]
                and test_result["recall"] is not None and test_result["recall"] >= minimum_recall)
    result = {"scope": "Original synthetic order-review exercise; no real orders, intervention or API deployment",
        "predeclared": {"cost_false_negative": 5, "cost_false_positive": 1,
            "threshold_candidates": thresholds, "threshold_tie_rule": "higher threshold if same validation cost",
            "minimum_test_recall": minimum_recall,
            "acceptance": "test cost strictly below validation-selected constant baseline AND recall>=.8",
            "feature_order_at_creation": ["distance", "queue", "promised_days", "fragile"]},
        "versions": {"python": platform.python_version(), "numpy": np.__version__, "sklearn": sklearn.__version__},
        "data_sha256": hashlib.sha256(json.dumps(records, sort_keys=True, separators=(",", ":")).encode()).hexdigest(),
        "split_ids": {"train": train_ids.tolist(), "validation": validation_ids.tolist(), "test": test_ids.tolist()},
        "training": {"count": len(train_ids), "scaler_n_samples_seen": int(model.named_steps["scale"].n_samples_seen_),
            "scaler_mean": model.named_steps["scale"].mean_.tolist(),
            "scaler_scale": model.named_steps["scale"].scale_.tolist(),
            "coefficients": model.named_steps["classifier"].coef_[0].tolist(),
            "intercept": float(model.named_steps["classifier"].intercept_[0])},
        "validation_candidates": candidates, "validation_choice": choice,
        "validation_constant_baselines": constant_candidates, "baseline_choice": baseline_choice,
        "frozen_test": test_result, "baseline_test": baseline_test,
        "test_predictions": [{"id": int(i), "label": int(y[i]), "probability": float(p), "decision": int(a)}
            for i, p, a in zip(test_ids, test_probability, test_prediction)],
        "acceptance_passed": bool(accepted),
        "limits": ["Cost units and .8 recall are teaching assumptions, not observed business economics.",
            "A model score does not prove that human review prevents a late delivery or produces savings.",
            "Random synthetic split assumes this constructed population; real deployment may require temporal/group splits.",
            "One held-out test was used after fixed validation selection; no test-based retuning or refit.",
            "No calibration, real-world fairness, privacy compliance, capacity constraint or confidence interval was established.",
            "Passing this toy acceptance rule is not authorization for production rollout."]}
    print(json.dumps(result, indent=2, allow_nan=False))


if __name__ == "__main__":
    main()
