import asyncio
from datetime import datetime

import toml

import rollbot
from commands import config


with open("secrets.toml", "r") as sfile:
    secrets = toml.load(sfile)


class TerminalBot(rollbot.Rollbot[str]):
    def __init__(self):
        super().__init__(
            config.extend(rollbot.CommandConfiguration(bangs=("!",))), "/tmp/terminalbot.db"
        )

    def read_config(self, key):
        if key == "democracy.candidates":
            return ["cand1", "cand2"]
        if key == "riddle.sleep":
            return 10

        cfg = secrets
        for part in key.split("."):
            cfg = cfg.get(part, None)
            if cfg is None:
                return None
        return cfg

    async def parse(self, raw):
        return rollbot.Message(
            origin_id="REPL",
            channel_id=".",
            sender_id=".",
            timestamp=datetime.now(),
            origin_admin=True,
            channel_admin=True,
            sender_name="User",
            text="!" + raw,
            attachments=[],
        )

    async def respond(self, res):
        if res.text is not None:
            print(res.text, flush=True)
        for att in res.attachments:
            print(f"Attached: {att.name}", flush=True)


async def run():
    bot = TerminalBot()
    await bot.on_startup()
    try:
        while True:
            await bot.on_message(input("> !"))
    except EOFError:
        pass
    finally:
        await bot.on_shutdown()


asyncio.run(run())
