"""Slack alert bot: post to a channel when a place's county forecast grade changes to D or worse.
pip install requests
export SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...   (Slack "Incoming Webhooks" app)
export GETFIXN_KEY=tfx_live_...
Run it on a schedule (see deploy recipes). Cost: locations x runs per day x $0.05. Data only, not advice.
"""
import os
import sys

import requests

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:
        changes = None
        text = "GetFixn bot paused: %s" % e
    if changes:
        text = "Storm forecast changes:\n" + "\n".join("- " + gf.line(c) for c in changes)
    elif changes is not None:
        return print("no changes")
    requests.post(os.environ["SLACK_WEBHOOK_URL"], json={"text": text}, timeout=20).raise_for_status()
    print(text)
    sys.exit(0 if changes is not None else 3)


if __name__ == "__main__":
    main()
