#!/usr/bin/env python3
"""Reference outline; not tested with a physical PPK2 or certified as evidence.

API checked against IRNAS/ppk2-api-python on 2026-11-06. Current is in uA.
Sample timestamps are reconstructed from the assumed device sample clock,
NOT host read times. The stream has no hardware timestamps or sequence IDs.
"""
import argparse
import csv
import hashlib
import json
import math
import time
from pathlib import Path


def positive(value):
    number = float(value)
    if not math.isfinite(number) or number <= 0:
        raise argparse.ArgumentTypeError("must be finite and positive")
    return number


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--port", required=True, help="PPK2 data port, not the DK UART")
    parser.add_argument("--seconds", type=positive, default=10)
    parser.add_argument("--sample-rate-hz", type=positive, default=100000,
                        help="verified device rate; does not configure hardware")
    parser.add_argument("--marker-channel", type=int, choices=range(8), default=0)
    parser.add_argument("--calls-per-window", type=int, required=True)
    parser.add_argument("--voltage-v", type=positive, default=3.0)
    parser.add_argument("--voltage-evidence", choices=("assumed", "measured"), default="assumed")
    parser.add_argument("--voltage-record", type=Path,
                        help="record supporting a measured CONSTANT voltage")
    parser.add_argument("--mode", choices=("ampere", "source"), default="ampere")
    parser.add_argument("--idle-ua", type=float, help="separately measured matched idle baseline")
    parser.add_argument("--output", type=Path, default=Path("ppk2-reference"))
    args = parser.parse_args()
    if args.calls_per_window < 1:
        parser.error("calls-per-window must be positive")
    if args.idle_ua is not None and not math.isfinite(args.idle_ua):
        parser.error("idle-ua must be finite")
    if args.voltage_evidence == "measured" and (not args.voltage_record or not args.voltage_record.is_file()):
        parser.error("measured constant voltage needs a voltage-record file")
    if not 0.8 <= args.voltage_v <= 5.0:
        parser.error("check PPK2 supported voltage range and DUT safe voltage")

    from ppk2_api.ppk2_api import PPK2_API  # pip install ppk2-api
    args.output.mkdir(parents=True, exist_ok=False)  # Never overwrite evidence.
    ppk = PPK2_API(args.port, timeout=0.1)
    ppk.get_modifiers()
    if args.mode == "source":
        ppk.use_source_meter()
    else:
        ppk.use_ampere_meter()
    # API requires a voltage value for calibration in both modes.
    # This setting is NOT evidence of the actual DUT rail voltage.
    ppk.set_source_voltage(round(args.voltage_v * 1000))
    # Deliberately do not toggle DUT power. Verify wiring and power manually.
    dt_us = 1e6 / args.sample_rate_hz
    windows, rejected = [], []
    index, previous, active, pending = 0, None, None, b""
    started = time.monotonic()
    raw_digest = hashlib.sha256()
    ppk.start_measuring()
    try:
        with (args.output / "samples.csv").open("w", newline="") as output, (args.output / "raw.bin").open("wb") as raw:
            writer = csv.writer(output)
            writer.writerow(["sample_index", "t_us_reconstructed", "current_ua", "marker"])
            while time.monotonic() - started < args.seconds:
                data = ppk.get_data()
                if not data:
                    time.sleep(0.001)
                    continue
                raw.write(data)
                raw_digest.update(data)
                pending += data
                usable = len(pending) // 4 * 4
                if not usable:
                    continue
                currents, bits = ppk.get_samples(pending[:usable])
                pending = pending[usable:]
                if len(currents) != len(bits):
                    raise RuntimeError("current/logic alignment failure; discard capture")
                marker_values = ppk.digital_channels(bits)[args.marker_channel]
                for current, high in zip(currents, marker_values):
                    if not math.isfinite(current):
                        raise RuntimeError("nonfinite current sample; discard capture")
                    writer.writerow([index, index * dt_us, current, high])
                    # Ignore an initial partial high interval; admit rising edges only.
                    if high and previous == 0:
                        active = {"start_sample": index, "samples": 0, "sum_ua": 0.0}
                    if high and active is not None:
                        active["samples"] += 1
                        active["sum_ua"] += current
                    if not high and previous == 1 and active is not None:
                        active["end_sample_exclusive"] = index
                        count = active["samples"]
                        if count < 10:
                            rejected.append({**active, "reason": "fewer than 10 samples; batch more calls"})
                        else:
                            # Rectangular integration: uA * us / 1000 = nC.
                            charge_nc = active.pop("sum_ua") * dt_us / 1000
                            per_call = charge_nc / args.calls_per_window
                            idle_corrected = None if args.idle_ua is None else (
                                charge_nc - args.idle_ua * count * dt_us / 1000
                            ) / args.calls_per_window
                            windows.append({**active, "calls": args.calls_per_window,
                                            "gross_charge_nc_per_decision": per_call,
                                            "idle_corrected_charge_nc_per_decision": idle_corrected,
                                            "derived_energy_nj_per_decision": per_call * args.voltage_v})
                        active = None
                    previous = high
                    index += 1
                if index and index % 100000 < len(currents):
                    print(f"Captured {index} samples; {len(windows)} complete windows", flush=True)
    finally:
        ppk.stop_measuring()
        ppk.ser.close()
    elapsed = time.monotonic() - started
    voltage_record_hash = None if not args.voltage_record else hashlib.sha256(args.voltage_record.read_bytes()).hexdigest()
    manifest = {
        "status": "reference_capture_requires_physical_validation",
        "boundary": "C1 only if firmware marks processed float features in RAM through class publication; exclude sensor/DSP/UART",
        "sample_rate_hz_assumed": args.sample_rate_hz, "sample_count": index,
        "host_elapsed_s": elapsed, "reconstructed_duration_s": index / args.sample_rate_hz,
        "voltage": {"value_v": args.voltage_v, "evidence": args.voltage_evidence,
                    "record_sha256": voltage_record_hash},
        "marker_channel": args.marker_channel, "raw_sha256": raw_digest.hexdigest(),
        "trailing_bytes": len(pending), "final_high_window_discarded": active is not None,
        "integration": "rectangular samples; gross includes marker/loop overhead; baseline only if supplied",
        "limitations": ["No hardware timestamp or sequence-gap validation", "GPIO edges quantized to sample clock",
                        "Short decision calls must be batched", "No automatic firmware/hash/probe binding"],
        "windows": windows, "rejected_windows": rejected,
    }
    (args.output / "summary.json").write_text(json.dumps(manifest, indent=2) + "\n")
    print(f"Saved {args.output}; {len(windows)} windows. Reference output, not a validated measurement receipt.")
    if not windows:
        raise SystemExit("No usable complete windows. Check marker wiring and calls per batch.")


if __name__ == "__main__":
    main()
