#!/usr/bin/env python3
"""
Compute -> Fill helper for SFT WSC

Given sampled phase values along a loop, estimate the degree (winding number) and
emit a minimal WSC JSON template with the computed integer.

Usage
  python3 compute_fill_wsc.py --period 86400 --id WSC-E-LDW-NEW --tier WTR-E --mechanism LDW --target embedded_loop --phases phases.txt

phases.txt should contain one phase value per line in [0,period).
"""
import argparse, json, math
from pathlib import Path

def unwrap(phases, P):
    if not phases:
        return []
    out = [phases[0]]
    for x in phases[1:]:
        prev = out[-1]
        k = round((prev - x) / P)
        cand = x + k*P
        # adjust neighbors for safety
        if abs((x + (k+1)*P) - prev) < abs(cand - prev):
            cand = x + (k+1)*P
        if abs((x + (k-1)*P) - prev) < abs(cand - prev):
            cand = x + (k-1)*P
        out.append(cand)
    return out

def degree(phases, P):
    lift = unwrap(phases, P)
    if not lift:
        return 0
    inc = lift[-1] - lift[0]
    return int(round(inc / P))

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--period", type=float, required=True)
    ap.add_argument("--id", required=True)
    ap.add_argument("--tier", choices=["WTR-G","WTR-E","WTR-C"], required=True)
    ap.add_argument("--mechanism", required=True)
    ap.add_argument("--target", required=True)
    ap.add_argument("--phases", required=True, help="path to phases.txt")
    ap.add_argument("--assumption", action="append", default=[], help="repeatable assumptions entries")
    args = ap.parse_args()

    P = args.period
    vals = [float(x.strip()) for x in Path(args.phases).read_text(encoding="utf-8").splitlines() if x.strip()]
    k = degree(vals, P)

    wsc = {
      "sft_version":"SFT-0.2.3",
      "certificate_id": args.id,
      "witness_tier": args.tier,
      "mechanism": args.mechanism,
      "target": args.target,
      "period_P": P,
      "witness_value": {"kind":"degree","integer": k, "notes":"computed from sampled phases via unwrap+increment"},
      "perturbation_model": "PM-2-lift-sup",
      "margins": {"LCM_pi": 1.0},
      "stability_modulus": {"k": k, "LCM_pi": 1.0, "target_rank": 1},
      "assumptions": args.assumption,
      "artifacts": {"theorem_refs": [], "files": []}
    }
    print(json.dumps(wsc, indent=2))

if __name__ == "__main__":
    main()
