"""Webhook relay, no SMS: when a county forecast grade changes, POST JSON to YOUR url(s)
(your own server, n8n, Make, Zapier, a Google Apps Script, anything that takes a webhook).
pip install requests
export RELAY_URLS=https://example.com/hook,https://other.example/hook   GETFIXN_KEY=tfx_live_...
export RELAY_SECRET=any-long-random-string   (optional: adds an HMAC-SHA256 X-Signature header so you can verify the sender)
"""
import hashlib
import hmac
import json
import os
import time

import requests

import gf_client as gf


def send(url, payload):
    body = json.dumps(payload, sort_keys=True).encode()
    headers = {"Content-Type": "application/json"}
    secret = os.environ.get("RELAY_SECRET")
    if secret:
        headers["X-Signature"] = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
    for attempt in range(3):
        try:
            if requests.post(url, data=body, headers=headers, timeout=20).status_code < 300:
                return True
        except requests.RequestException:
            pass
        time.sleep(2 ** attempt)
    return False


def main():
    locs = gf.load_locations(os.environ.get("LOCATIONS", "locations.json"))
    changes = gf.check(locs, os.environ.get("STATE", "state.json"), alert_at=os.environ.get("ALERT_AT", "D"))
    if not changes:
        return print("no changes")
    payload = {"source": "getfixn-example", "note": "forecast data, not advice", "changes": changes}
    for url in os.environ["RELAY_URLS"].split(","):
        print(url.split("/")[2], "ok" if send(url.strip(), payload) else "FAILED")


if __name__ == "__main__":
    main()
