"""Telegram bot, long polling, no extra library. pip install requests
export TELEGRAM_TOKEN=...  GETFIXN_KEY=tfx_live_...   (token from @BotFather)
/risk Austin   -> county forecast grade ($0.05)      /weather 30.27,-97.74 -> live weather ($0.0002)
Data only, not advice.
"""
import os
import time

import requests

import gf_client as gf

API = "https://api.telegram.org/bot%s/" % os.environ["TELEGRAM_TOKEN"]
LOCS = gf.load_locations(os.environ.get("LOCATIONS", "locations.json"))


def reply(text, update):
    requests.post(API + "sendMessage", json={"chat_id": update["message"]["chat"]["id"], "text": text}, timeout=20)


def handle(update):
    parts = (update.get("message", {}).get("text") or "").split(None, 1)
    if not parts or not parts[0].startswith("/"):
        return
    cmd, arg = parts[0].split("@")[0], (parts[1] if len(parts) > 1 else "")
    try:
        if cmd == "/risk":
            loc = gf.pick(LOCS, arg)
            r = gf.grades([loc])[0]
            reply("%s: county forecast grade %s (%s, %s). A forecast, not a certainty." % (
                loc["label"], r.get("grade"), r.get("county"), r.get("state")), update)
        elif cmd == "/weather":
            loc = gf.pick(LOCS, arg)
            r = gf.weather([loc])[0]
            reply("%s: %s F, %d active alert(s)" % (
                loc["label"], (r.get("current") or {}).get("temperature_f"), len(r.get("alerts") or [])), update)
        else:
            reply("Try /risk Austin or /weather 30.27,-97.74. Saved places: " + ", ".join(l["label"] for l in LOCS), update)
    except gf.LowBalance as e:
        reply("Balance problem: %s" % e, update)
    except (ValueError, RuntimeError) as e:
        reply("Could not do that: %s" % e, update)


def main():
    offset = None
    while True:
        try:
            r = requests.get(API + "getUpdates", params={"timeout": 30, "offset": offset}, timeout=40).json()
            for u in r.get("result", []):
                offset = u["update_id"] + 1
                handle(u)
        except requests.RequestException:
            time.sleep(5)  # Telegram or the network hiccuped, try again


if __name__ == "__main__":
    main()
