"""Discord slash-command bot: /risk and /weather for a saved place or "lat,lon".
pip install discord.py requests
export DISCORD_TOKEN=... GETFIXN_KEY=tfx_live_...   (a bot token from the Discord developer portal)
Each /risk costs $0.05, each /weather $0.0002. Data only, not advice.
"""
import asyncio
import os

import discord
from discord import app_commands

import gf_client as gf

LOCS = gf.load_locations(os.environ.get("LOCATIONS", "locations.json"))


class Bot(discord.Client):
    def __init__(self):
        super().__init__(intents=discord.Intents.default())
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self):
        await self.tree.sync()


bot = Bot()


async def run(inter, fn, fmt, place):
    await inter.response.defer()  # the API call can take a few seconds
    try:
        loc = gf.pick(LOCS, place)
        r = (await asyncio.to_thread(fn, [loc]))[0]
        await inter.followup.send(fmt(loc, r))
    except gf.LowBalance as e:
        await inter.followup.send("Balance problem: %s" % e)
    except (ValueError, RuntimeError) as e:
        await inter.followup.send("Could not do that: %s" % e)


@bot.tree.command(description="County forecast grade A-F for a saved place or lat,lon ($0.05)")
async def risk(inter: discord.Interaction, place: str):
    await run(inter, gf.grades, lambda l, r: "**%s**: county forecast grade **%s** (%s, %s). A forecast, not a certainty." % (
        l["label"], r.get("grade"), r.get("county"), r.get("state")), place)


@bot.tree.command(description="Model-Based Weather by Address for a saved place or lat,lon ($0.0002)")
async def weather(inter: discord.Interaction, place: str):
    await run(inter, gf.weather, lambda l, r: "**%s**: %s F, %d active alert(s)" % (
        l["label"], (r.get("current") or {}).get("temperature_f"), len(r.get("alerts") or [])), place)


if __name__ == "__main__":
    bot.run(os.environ["DISCORD_TOKEN"])
