import logging
from os import environ

from fastapi import FastAPI, Request
from mastodon import Mastodon, StreamListener

MASTODON_ACCESS_TOKEN = environ.get("MASTODON_ACCESS_TOKEN")
MASTODON_API_BASE_URL = environ.get("MASTODON_API_BASE_URL")

APP_LOG_LEVEL = environ.get("APP_LOG_LEVEL")
if APP_LOG_LEVEL == "info":
    APP_LOG_LEVEL = logging.INFO
elif APP_LOG_LEVEL == "debug":
    APP_LOG_LEVEL = logging.DEBUG
else:
    APP_LOG_LEVEL = logging.INFO

mastodon = Mastodon(
    access_token=MASTODON_ACCESS_TOKEN,
    api_base_url=f"https://{MASTODON_API_BASE_URL}",
)

log = logging.getLogger("uvicorn")
log.setLevel(APP_LOG_LEVEL)

app = FastAPI()
app.state.log = log


class PubspaceListener(StreamListener):
    def on_update(self, status):
        log.info(status)


mastodon.stream_hashtag("pubspace", PubspaceListener(), run_async=True)


@app.get("/")
async def home(request: Request):
    app.state.log.info(await request.json())


@app.get("/healthz")
async def healthz(request: Request):
    return {"detail": "ALL ENGINES FIRING"}