#!/usr/bin/env python3
"""
Infer degree (winding number) from sampled phases on a loop.

Input: phases in [0,P) one per line
Output: integer degree k

This is the same logic as compute_fill_wsc, provided as a standalone tool.
"""
import argparse, 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
        # local adjustment
        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 main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--period", type=float, required=True)
    ap.add_argument("--phases", required=True)
    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()]
    lift = unwrap(vals, P)
    if not lift:
        print(0)
        return
    k = int(round((lift[-1] - lift[0]) / P))
    print(k)

if __name__ == "__main__":
    main()
