"""Reconstruct regimes_*.pt from an exp4_*.log printed table (the scan's
torch.save crashes on its CWD-relative "results/" path — known bug; the
printed table is the durable artifact). Generalizes parse_e4b_regimes.py.

Usage: parse_regimes_log.py LOG OUT [--layers N] [--note TEXT]
"""
import argparse
import re

import torch

ap = argparse.ArgumentParser()
ap.add_argument("log")
ap.add_argument("out")
ap.add_argument("--layers", type=int, default=None,
                help="assert this many table rows were parsed")
ap.add_argument("--note", default=None,
                help="provenance note stored in the tensor dict")
args = ap.parse_args()

sensor, motor, persist, content = [], [], [], []
pat = re.compile(
    r"^L\s*(\d+) \| ([\d.]+)\s*#* *\| ([\d.]+)\s*#* *\| ([\d.]+) \| ([\d.]+)")
for line in open(args.log):
    m = pat.match(line.strip())
    if m:
        i, s, mo, p, c = m.groups()
        assert int(i) == len(sensor), f"non-contiguous row L{i}"
        sensor.append(float(s))
        motor.append(float(mo))
        persist.append(float(p))
        content.append(float(c))
if args.layers is not None:
    assert len(sensor) == args.layers, len(sensor)
note = args.note or f"reconstructed from {args.log}"
torch.save({"sensor": torch.tensor(sensor), "motor": torch.tensor(motor),
            "persist": torch.tensor(persist),
            "content": torch.tensor(content), "note": note}, args.out)
print(f"saved {len(sensor)} layers -> {args.out}")
print("sensor peak: L%d = %.2f" % (sensor.index(max(sensor)), max(sensor)))
print("persist peak: L%d = %.2f" % (persist.index(max(persist)),
                                    max(persist)))
print("motor >=0.1 from: L%s" % next(
    (i for i, v in enumerate(motor) if v >= 0.1), "never"))
