"""Original stdlib-only local provenance exercise, not an MLflow/DVC implementation."""
import csv
import hashlib
import io
import json
import math
import platform
import random
from pathlib import Path

BASE = Path(__file__).resolve().parent


def digest(data):
    return hashlib.sha256(data).hexdigest()


def canonical(value):
    return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()


def csv_bytes(rows):
    stream = io.StringIO(newline="")
    writer = csv.writer(stream, lineterminator="\n")
    writer.writerow(["id", "x", "y"])
    writer.writerows(rows)
    return stream.getvalue().encode()


def parse(raw):
    records = list(csv.DictReader(io.StringIO(raw.decode())))
    rows = [{"id": int(r["id"]), "x": float(r["x"]), "y": float(r["y"])} for r in records]
    if len({r["id"] for r in rows}) != len(rows):
        raise ValueError("Duplicate row ID")
    if not all(math.isfinite(r[k]) for r in rows for k in ("x", "y")):
        raise ValueError("Nonfinite data")
    return sorted(rows, key=lambda r: r["id"])


def experiment(raw, seed=17):
    rows = parse(raw)
    shuffled_ids = [r["id"] for r in rows]
    random.Random(seed).shuffle(shuffled_ids)
    test_ids = sorted(shuffled_ids[:6])
    train_ids = sorted(shuffled_ids[6:])
    train = [r for r in rows if r["id"] in train_ids]
    test = [r for r in rows if r["id"] in test_ids]
    # Closed-form univariate OLS with intercept, fit on training rows only.
    mean_x = math.fsum(r["x"] for r in train) / len(train)
    mean_y = math.fsum(r["y"] for r in train) / len(train)
    denominator = math.fsum((r["x"] - mean_x)**2 for r in train)
    if denominator == 0:
        raise ValueError("Training x has zero variance")
    slope = math.fsum((r["x"] - mean_x) * (r["y"] - mean_y) for r in train) / denominator
    intercept = mean_y - slope * mean_x
    predictions = [{"id": r["id"], "prediction": slope * r["x"] + intercept} for r in test]
    mse = math.fsum((p["prediction"] - r["y"])**2 for p, r in zip(predictions, test)) / len(test)
    result = {"model": {"slope": slope, "intercept": intercept},
              "test_predictions": predictions, "test_mse": mse}
    receipt = {"raw_data_sha256": digest(raw), "normalized_rows_sha256": digest(canonical(rows)),
        "code_sha256": digest(Path(__file__).read_bytes()),
        "recipe": {"model": "univariate OLS with intercept; train-only closed form",
                   "split_seed": seed, "test_count": 6, "row_policy": "sort unique integer IDs before shuffle"},
        "train_ids": train_ids, "test_ids": test_ids,
        "environment": {"python": platform.python_version(), "implementation": platform.python_implementation(),
                        "platform": platform.system(), "machine": platform.machine()},
        "result_sha256": digest(canonical(result))}
    return receipt, result


def check_inputs(raw, receipt, seed):
    checks = {"raw_data": digest(raw) == receipt["raw_data_sha256"],
              "code": digest(Path(__file__).read_bytes()) == receipt["code_sha256"],
              "split_seed": seed == receipt["recipe"]["split_seed"]}
    # An integrity check against a trusted saved receipt, not proof of authorship/security.
    if not all(checks.values()):
        raise ValueError("Input mismatch: " + ",".join(k for k, same in checks.items() if not same))


def main():
    rows = [(i, i - 12, 2.5 * (i - 12) + 4 + ((i * 7) % 5 - 2) * .2) for i in range(24)]
    raw = csv_bytes(rows)
    receipt, result = experiment(raw)
    check_inputs(raw, receipt, 17)
    replay_receipt, replay_result = experiment(raw)
    assert canonical(receipt) == canonical(replay_receipt)
    assert canonical(result) == canonical(replay_result)
    reordered = csv_bytes(list(reversed(rows)))
    reorder_receipt, reorder_result = experiment(reordered)
    assert reorder_receipt["raw_data_sha256"] != receipt["raw_data_sha256"]
    assert reorder_receipt["normalized_rows_sha256"] == receipt["normalized_rows_sha256"]
    assert canonical(reorder_result) == canonical(result)
    # Change one known training target; same filename and seed would hide this without a receipt.
    changed_id = receipt["train_ids"][0]
    changed_rows = [(i, x, y + 1 if i == changed_id else y) for i, x, y in rows]
    changed = csv_bytes(changed_rows)
    _, changed_result = experiment(changed)
    assert canonical(changed_result) != canonical(result)
    mismatches = []
    for name, candidate, seed in [("changed_training_target", changed, 17),
                                   ("same_rows_reordered", reordered, 17),
                                   ("changed_split_seed", raw, 18)]:
        try:
            check_inputs(candidate, receipt, seed)
        except ValueError as error:
            mismatches.append({"case": name, "rejected": str(error)})
        else:
            raise AssertionError("Expected input mismatch")
    out = BASE / "artifacts"
    out.mkdir(exist_ok=True)
    (out / "data.csv").write_bytes(raw)
    (out / "receipt.json").write_bytes(canonical(receipt) + b"\n")
    (out / "result.json").write_bytes(canonical(result) + b"\n")
    print(json.dumps({"scope": "Original 24-row synthetic local OLS provenance exercise; one existing environment",
        "receipt": receipt, "result": result,
        "checks": {"same_environment_replay_receipt_and_result_byte_exact": True,
            "reordered_raw_bytes_differ": True, "reordered_normalized_rows_and_result_same": True,
            "changed_training_target_id": changed_id, "changed_target_changes_result": True},
        "rejected_inputs": mismatches,
        "limits": ["Hashes check bytes against a trusted receipt, not source trust or data quality.",
            "Normalization is this explicit schema/ID policy, not a universal semantic equivalence test.",
            "Environment metadata is partial, not an OS/library/container lock or cross-platform guarantee.",
            "A seed alone does not identify data, code, split IDs, environment or numeric behavior.",
            "Toy held-out MSE is not production quality, fairness or leakage assurance.",
            "No MLflow server, DVC remote, cloud registry or external service was installed or tested."]},
        indent=2, allow_nan=False))


if __name__ == "__main__":
    main()
