"""Record raw/fetch-params.json once per research dir; a resumed run never rewrites how the existing data was fetched.

usage: python3 fetch_params.py <path> '<json params>'

First run: writes the params with started_utc. Same params again: keeps the file and appends the time to resumed_utc.
Different params while the file exists: exit 2 — the comments already on disk were fetched another way, so a new cap
or sort goes into a new research dir (the coverage sentence would otherwise describe the wrong fetch)."""
import datetime as dt, json, os, sys

KEYS = ('tool', 'mode', 'max_comments', 'comment_sort', 'cookies')


def record(path, params):
    now = dt.datetime.now(dt.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
    if os.path.exists(path):
        old = json.load(open(path))
        diff = {k: (old.get(k), params.get(k)) for k in KEYS if old.get(k) != params.get(k)}
        if diff:
            return 2, f'{path} was written with other fetch settings {diff}: use a new research dir for a new cap/sort'
        old.setdefault('resumed_utc', []).append(now)
        json.dump(old, open(path, 'w'), indent=1)
        return 0, f'resumed with the recorded settings (started {old.get("started_utc")})'
    json.dump({**params, 'started_utc': now}, open(path, 'w'), indent=1)
    return 0, 'recorded'


if __name__ == '__main__':
    if len(sys.argv) != 3: sys.exit(__doc__)
    rc, msg = record(sys.argv[1], json.loads(sys.argv[2]))
    print(msg, file=sys.stderr if rc else sys.stdout)
    sys.exit(rc)
