"""Re-ask for the handles the walk lost to a 429, one at a time, and rewrite the CSV.

Six workers was too fast for the registry's limiter in places: 74 of 2,300 rows
came back 429 after four backoffs on the first run. Those rows are re-fetched
here serially with a second between them, because a citizen counted as "never
sealed" because the server was busy would be a fabricated result, not a floor.
"""
import csv
import os
import pathlib
import sys
import time

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from fetch_seals import FIELDS, get                     # noqa: E402

OUT = pathlib.Path(os.path.expanduser("~/data/1f916-quiet"))
PAUSE = 1.0


def main():
    path = OUT / "seals.csv"
    rows = list(csv.DictReader(open(path)))
    failed = [r for r in rows if r.get("error")]
    print(f"{len(failed)} rows to retry of {len(rows)}", flush=True)
    fixed = 0
    for i, r in enumerate(failed, 1):
        d = get(f"/api/seals?citizen={r['handle']}")
        if d.get("_error"):
            r["error"] = d["_error"]
        else:
            latest = d.get("latest") or {}
            r.update({
                "latest_seal_id": latest.get("id") or "",
                "latest_label": latest.get("label") or "",
                "sealed_at": latest.get("sealed_at") or "",
                "checks": latest.get("checks") or "",
                "last_checked_at": latest.get("last_checked_at") or "",
                "rows_seen": len(d.get("seals") or []),
                "error": "",
            })
            fixed += 1
        if i % 20 == 0:
            print(f"  {i} of {len(failed)}", flush=True)
        time.sleep(PAUSE)
    with open(path, "w", newline="") as fh:
        writer = csv.DictWriter(fh, fieldnames=FIELDS)
        writer.writeheader()
        writer.writerows(rows)
    still = sum(1 for r in rows if r.get("error"))
    print(f"rewrote {path}: {fixed} recovered, {still} still failing")


if __name__ == "__main__":
    main()
