"""Scheduled monitor: one run = one check. Prints changes and appends them to alerts.jsonl.
pip install requests
export GETFIXN_KEY=tfx_live_...
Exit codes: 0 fine, 3 balance/key problem (so cron mail or CI can tell you to top up).
The forecast refreshes 4 times a day, so running more often than every 6 hours only costs you money.
"""
import json
import os
import sys
import time

import gf_client as gf


def main():
    locs = gf.load_locations(os.environ.get("LOCATIONS", "locations.json"))
    try:
        changes = gf.check(locs, os.environ.get("STATE", "state.json"), alert_at=os.environ.get("ALERT_AT", "D"))
    except gf.LowBalance as e:
        print("PAUSED:", e)
        sys.exit(3)
    with open("alerts.jsonl", "a") as f:
        for c in changes:
            print(gf.line(c))
            f.write(json.dumps(dict(c, ts=int(time.time()))) + "\n")
    if not changes:
        print("no changes")


if __name__ == "__main__":
    main()
