"""Summarize M-001 v0.1 event pairs. Copyright 2026 15 Research Lab. SPDX-License-Identifier: MIT"""
import argparse
import csv
from decimal import Decimal, InvalidOperation
from hashlib import sha256
import json
from pathlib import Path
from statistics import median


FIELDS = (
    "trial_id", "source_ref", "t_request_s", "x_request_mm", "t_rest_s",
    "x_rest_mm", "approach_speed_mm_s", "status", "reason",
)


def read_number(row, field):
    try:
        value = Decimal(row[field])
    except InvalidOperation as exc:
        raise ValueError(f"{row['trial_id']}: {field} needs a decimal value") from exc
    if not value.is_finite():
        raise ValueError(f"{row['trial_id']}: {field} must be finite")
    return value


def summarize(run_path):
    run = json.loads(run_path.read_text(encoding="utf-8"))
    if (run["method_id"], run["method_version"]) != ("M-001", "0.1"):
        raise ValueError("This analysis reads M-001 v0.1 only")
    if run["source_type"] not in ("synthetic", "empirical"):
        raise ValueError("Declare the event records synthetic or empirical")
    source = run_path.parent / run["input"]
    distances = []
    records = []
    seen = set()
    with source.open(newline="", encoding="utf-8-sig") as stream:
        reader = csv.DictReader(stream)
        names = reader.fieldnames or []
        if len(names) != len(set(names)) or not set(FIELDS) <= set(names):
            raise ValueError("The capture table requires unique M-001 v0.1 column names")
        for row in reader:
            if None in row or any(value is None for value in row.values()):
                raise ValueError(f"Row {reader.line_num} has the wrong field count")
            item = {field: row[field].strip() for field in FIELDS}
            trial = item["trial_id"]
            if not trial or trial in seen or not item["source_ref"]:
                raise ValueError(f"Row {reader.line_num} needs a unique trial ID and source reference")
            seen.add(trial)
            state = item["status"]
            if state not in ("valid", "excluded") or (state == "excluded" and not item["reason"]):
                raise ValueError(f"{trial}: declare validity and give a reason for exclusion")
            numbers = {}
            for field in ("t_request_s", "x_request_mm", "t_rest_s", "x_rest_mm", "approach_speed_mm_s"):
                if item[field] or state == "valid":
                    numbers[field] = read_number(item, field)
            distance = None
            if state == "valid":
                if numbers["t_rest_s"] < numbers["t_request_s"]:
                    raise ValueError(f"{trial}: standstill precedes the request")
                distance = numbers["x_rest_mm"] - numbers["x_request_mm"]
                if distance < 0 or numbers["approach_speed_mm_s"] < 0:
                    raise ValueError(f"{trial}: review the signed measurements and positive approach axis")
                distances.append(distance)
            records.append({
                "trial_id": trial,
                "x_request_mm": float(numbers["x_request_mm"]) if "x_request_mm" in numbers else None,
                "x_rest_mm": float(numbers["x_rest_mm"]) if "x_rest_mm" in numbers else None,
                "travel_mm": float(distance) if distance is not None else None,
                "status": state,
                "reason": item["reason"],
            })
    return {
        "method_id": run["method_id"], "method_version": run["method_version"],
        "finding_id": run["finding_id"], "run_id": run["run_id"], "source_type": run["source_type"],
        "input_sha256": sha256(source.read_bytes()).hexdigest(),
        "unit": "mm", "n_total": len(records), "n_valid": len(distances),
        "n_excluded": len(records) - len(distances),
        "median_mm": float(median(distances)) if distances else None,
        "min_mm": float(min(distances)) if distances else None,
        "max_mm": float(max(distances)) if distances else None,
        "rows": records,
    }


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("run", type=Path, help="Run JSON with 'input' relative to itself")
    args = parser.parse_args()
    try:
        result = summarize(args.run)
        print(json.dumps(result, indent=2, ensure_ascii=False, allow_nan=False))
    except (KeyError, ValueError, OSError, csv.Error) as error:
        parser.exit(1, f"{error}\n")
