#!/usr/bin/env python3
"""Compare a fixed centroid rule and a training-only nearest-centroid fit.
Original course teaching example. SPDX-License-Identifier: MIT.
"""
import argparse
from collections import Counter
import math
import platform
import statistics
from time import perf_counter
from common import flag, number, output_dir, read_csv, write_csv, write_json

LABELS = ("left", "center", "right")
FEATURES = ("dark_fraction", "centroid_x")


def load_features(path):
    rows = read_csv(path, ["path", "label", "session", "split", "has_dark", *FEATURES])
    groups, paths, hashes = {}, {}, {}
    for index, row in enumerate(rows, start=2):
        if row["label"] not in LABELS or row["split"] not in ("train", "test"):
            raise ValueError(f"row {index}: unexpected label/split")
        row["session"] = (row["session"] or "").strip()
        if not row["session"] or not row["path"]:
            raise ValueError(f"row {index}: session/path is empty")
        for mapping, key, description in ((groups, row["session"], "session"),
                                          (paths, row["path"], "image path"),
                                          (hashes, row.get("sha256"), "image hash")):
            if key:
                if key in mapping and mapping[key] != row["split"]:
                    raise ValueError(f"Cross-split {description} leakage: {key}")
                mapping[key] = row["split"]
        row["has_dark"] = flag(row["has_dark"], f"row {index} has_dark")
        row["dark_fraction"] = number(row["dark_fraction"], "dark_fraction")
        if not 0 <= row["dark_fraction"] <= 1:
            raise ValueError("dark_fraction must be 0..1")
        if row["has_dark"]:
            row["centroid_x"] = number(row["centroid_x"], "centroid_x")
            if not 0 <= row["centroid_x"] <= 1 or row["dark_fraction"] <= 0:
                raise ValueError("Dark pixels require centroid_x 0..1 and dark_fraction > 0")
        elif row["dark_fraction"] != 0 or row["centroid_x"] not in ("", None):
            raise ValueError("has_dark=0 requires dark_fraction=0 and empty centroid_x")
    return rows


def score(truth, guesses):
    confusion = {label: {predicted: 0 for predicted in LABELS} for label in LABELS}
    for label, predicted in zip(truth, guesses):
        confusion[label][predicted] += 1
    support = Counter(truth)
    return {"test_images": len(truth), "correct": sum(a == b for a, b in zip(truth, guesses)),
            "accuracy": sum(a == b for a, b in zip(truth, guesses)) / len(truth),
            "support_by_true_class": {label: support[label] for label in LABELS},
            "confusion_rows_true_columns_predicted": confusion}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("features_csv")
    parser.add_argument("--out", required=True)
    args = parser.parse_args()
    try:
        rows = load_features(args.features_csv)
        train = [row for row in rows if row["split"] == "train" and row["has_dark"]]
        test = [row for row in rows if row["split"] == "test" and row["has_dark"]]
        for split, subset in (("train", train), ("test", test)):
            if set(row["label"] for row in subset) != set(LABELS):
                raise ValueError(f"{split} needs at least one image with dark pixels for EACH of left/center/right")
        start = perf_counter()
        means = [statistics.mean(row[name] for row in train) for name in FEATURES]
        # A constant training feature gets scale 1; test rows never set the scale.
        scales = [statistics.pstdev(row[name] for row in train) or 1.0 for name in FEATURES]

        def standardize(row):
            return [(row[name] - mean) / scale for name, mean, scale in zip(FEATURES, means, scales)]

        centers = {}
        for label in LABELS:
            members = [standardize(row) for row in train if row["label"] == label]
            centers[label] = [statistics.mean(member[i] for member in members) for i in range(len(FEATURES))]
        fit_ms = (perf_counter() - start) * 1000
        start = perf_counter()
        learned = []
        for row in test:
            point = standardize(row)
            learned.append(min(LABELS, key=lambda label: math.dist(point, centers[label])))
        learned_ms = (perf_counter() - start) * 1000
        start = perf_counter()
        fixed = ["left" if row["centroid_x"] < 1/3 else
                 "right" if row["centroid_x"] > 2/3 else "center" for row in test]
        fixed_ms = (perf_counter() - start) * 1000
        excluded = [row for row in rows if not row["has_dark"]]
        out = output_dir(args.out)
        write_csv(out / "predictions.csv", ["path", "session", "truth", "fixed_rule", "nearest_centroid"],
                  [{"path": row["path"], "session": row["session"], "truth": row["label"],
                    "fixed_rule": rule, "nearest_centroid": model}
                   for row, rule, model in zip(test, fixed, learned)])
        write_json(out / "metrics.json", {
            "python": platform.python_version(), "input": args.features_csv,
            "features": list(FEATURES), "training_images": len(train), "test_images": len(test),
            "train_sessions": sorted({row["session"] for row in rows if row["split"] == "train"}),
            "test_sessions": sorted({row["session"] for row in rows if row["split"] == "test"}),
            "train_support": dict(Counter(row["label"] for row in train)),
            "excluded_no_dark": {split: {label: sum(row["split"] == split and row["label"] == label for row in excluded)
                                          for label in LABELS} for split in ("train", "test")},
            "fit": {"training_means": means, "training_scales": scales, "standardized_class_centroids": centers},
            "fixed_rule": score([row["label"] for row in test], fixed),
            "nearest_centroid": score([row["label"] for row in test], learned),
            "timing_ms": {"nearest_centroid_fit": fit_ms, "nearest_centroid_test_predict": learned_ms,
                          "fixed_rule_test_predict": fixed_ms},
            "declared_sources": sorted({row.get("source") or "unspecified" for row in rows}),
            "notes": ["Each session stays in one split. Duplicate image paths/hashes across splits are rejected when supplied.",
                      "Scale and class means use training rows only. Test labels are used only for scoring.",
                      "Rule fixed before testing: x<1/3 left, x>2/3 right, otherwise center. Do not tune on this test split.",
                      "No-dark images are excluded and counted; accuracy is conditional on retained images, not full-system success.",
                      "Timing is a single local perf_counter measurement, excludes loading/features, and is noisy on tiny batches.",
                      "Near frames in a session are correlated. Image count is not an independent-trial count; synthetic scores are not physical performance."]})
        print(f"Evaluated {len(test)} retained test images; excluded {len(excluded)} no-dark images overall; wrote {out}")
    except (OSError, ValueError) as exc:
        parser.error(str(exc))


if __name__ == "__main__":
    main()
