# pyright: reportMissingModuleSource=false
# pyright: reportUnusedExpression=false
# ruff: noqa: B015


from __future__ import annotations

import json
from dataclasses import dataclass
from enum import Enum, StrEnum
from typing import TYPE_CHECKING, cast

from browser import DOMEvent, aio, document, local_storage, window
from browser.html import BUTTON, DIV, FORM, OPTION, SELECT, P
from browser.widgets.dialog import InfoDialog

if TYPE_CHECKING:
    from collections.abc import Callable, Coroutine
    from typing import Any

    from browser.aio import _Request
    from browser.html import INPUT, _HTMLElement
    from browser.widgets.dialog import _ToString


class HTTPError(Exception):
    def __init__(self, message: str) -> None:
        self.message = message
        super().__init__(message)

    def __str__(self) -> str:
        return f"HTTP Error {self.message}"


class StatusCode(Enum):
    OK = 200
    TOO_MANY_REQUESTS = 429
    UNAUTHORIZED = 401


class FortuneURI(StrEnum):
    """Format strings for getting fortunes :3"""

    RANDOM = "/random"
    BY_ID = "/id/%d"
    BY_SEARCH = "/search"
    BY_CATEGORY = "category/%s"
    SUBMIT = "/submit"


@dataclass
class Fortune:
    content: str
    category: Category
    author: str | None = None


class Category(Enum):
    UserSubmitted = "user-submitted"
    Art = "art"
    AsciiArt = "ascii-art"
    Computers = "computers"
    Cookie = "cookie"
    Debian = "debian"
    Definitions = "definitions"
    Disclaimer = "disclaimer"
    Drugs = "drugs"
    Education = "education"
    Ethnic = "ethnic"
    Food = "food"
    Fortunes = "fortunes"
    Goedel = "goedel"
    Humorists = "humorists"
    Kids = "kids"
    Knghtbrd = "knghtbrd"
    Law = "law"
    Linux = "linux"
    Literature = "literature"
    Love = "love"
    Magic = "magic"
    Medicine = "medicine"
    MenWomen = "men-women"
    Miscellaneous = "miscellaneous"
    News = "news"
    Paradoxum = "paradoxum"
    People = "people"
    Perl = "perl"
    Pets = "pets"
    Platitudes = "platitudes"
    Politics = "politics"
    Pratchett = "pratchett"
    Riddles = "riddles"
    RulesOfAcquisition = "rules-of-acquisition"
    Science = "science"
    ShlomifFav = "shlomif-fav"
    SongsPoems = "songs-poems"
    Sports = "sports"
    Startrek = "startrek"
    Tao = "tao"
    TheXFilesTaglines = "the-x-files-taglines"
    TranslateMe = "translate-me"
    Wisdom = "wisdom"
    Work = "work"
    Zippy = "zippy"


@dataclass
class State:
    fortunes_content: DIV
    api_key: str | None = None

    def init_registration_button(self) -> None:
        async def register(e: DOMEvent) -> None:
            e.preventDefault()

            if self.api_key:
                error_dialog("Already registered!")
                return

            res = await aio.post("/register")
            if res.status != StatusCode.OK.value:
                error_dialog(HTTPError(res.statusText))
                return

            self.api_key = str(res.data).replace('"', "")

            success_dialog("Registered an API key!")

        but = document.getElementById("registration")
        but.bind("click", lambda e: aio.run(register(e)))

    def clear_fortunes(self) -> None:
        self.fortunes_content.innerHTML = ""

    def check_response(self, res: _Request) -> bool:
        if res.status == StatusCode.UNAUTHORIZED.value:
            self.api_key = ""
            error_dialog("Invalid api key, re-register.")
            return False

        if res.status != StatusCode.OK.value:
            error_dialog(HTTPError(res.statusText))
            return False

        return True

    @staticmethod
    async def get_random() -> Fortune | None:
        res = await aio.get(FortuneURI.RANDOM.value)

        if res.status != StatusCode.OK.value:
            error_dialog(HTTPError(res.statusText))
            return None

        content = json.loads(res.data)

        return Fortune(**content)

    @staticmethod
    async def get_by_id(id: str) -> Fortune | None:
        try:
            int(id)
        except TypeError:
            error_dialog("Please enter a real number!")
            return None

        res = await aio.get(FortuneURI.BY_ID.value % int(id))

        if res.status != StatusCode.OK.value:
            error_dialog(HTTPError(res.statusText))
            return None

        content = json.loads(res.data)

        return Fortune(**content)

    async def get_by_search(
        self,
        q: str,
        limit: int | None = None,
    ) -> list[Fortune] | None:
        if not self.api_key:
            error_dialog("Register first!")
            return None

        headers = {"Authorization": f"Bearer {self.api_key}"}
        data: dict[str | bytes, str | bytes] = {"q": q}

        if limit:
            data["limit"] = str(limit)

        res = await aio.get(
            FortuneURI.BY_SEARCH.value,
            data=data,
            headers=headers,
        )

        if not self.check_response(res):
            return None

        content = json.loads(res.data)

        return [Fortune(**raw) for raw in content]

    async def get_by_category(
        self,
        category: Category,
        limit: int | None = None,
    ) -> list[Fortune] | None:
        if not self.api_key:
            error_dialog("Register first!")
            return None

        headers = {"Authorization": f"Bearer {self.api_key}"}

        res = await aio.get(
            FortuneURI.BY_CATEGORY.value % category.value,
            data={"limit": str(limit)} if limit else {},
            headers=headers,
        )

        if not self.check_response(res):
            return None

        content = json.loads(res.data)

        return [Fortune(**raw) for raw in content]

    async def submit(self, content: str, author: str | None) -> None:
        if not self.api_key:
            error_dialog("Register first!")
            return

        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
        }

        data = json.dumps({"content": content, "author": author})
        print(data)

        res = await aio.post(
            FortuneURI.SUBMIT.value,
            data=data,
            headers=headers,
        )

        if not self.check_response(res):
            return

        id = json.loads(res.data)["id"]

        success_dialog(f"Successfully submitted! ID: {id}")

    async def callback_random(self, e: DOMEvent) -> None:
        e.preventDefault()

        if not self.api_key:
            error_dialog("Register first!")
            return

        fortune = await self.get_random()

        if not fortune:
            return

        self.clear_fortunes()
        self.fortunes_content <= create_fortune(fortune)

        return

    def callback_search(
        self,
        query_el: INPUT,
        limit_el: INPUT,
    ) -> Callable[[DOMEvent], Coroutine[Any, Any, None]]:
        async def _f(e: DOMEvent) -> None:
            e.preventDefault()
            fortunes = await self.get_by_search(
                cast("str", query_el.value),
                cast("int | None", limit_el.value),
            )
            if not fortunes:
                return

            self.clear_fortunes()
            self.fortunes_content <= [
                create_fortune(fortune) for fortune in fortunes
            ]

        return _f

    def callback_category(
        self,
        category_el: SELECT,
        limit_el: INPUT,
    ) -> Callable[[DOMEvent], Coroutine[Any, Any, None]]:
        async def _f(e: DOMEvent) -> None:
            e.preventDefault()
            fortunes = await self.get_by_category(
                Category(category_el.value),
                cast("int | None", limit_el.value),
            )

            if not fortunes:
                return

            self.clear_fortunes()
            self.fortunes_content <= [
                create_fortune(fortune) for fortune in fortunes
            ]

        return _f

    def callback_id(
        self,
        id_el: INPUT,
    ) -> Callable[[DOMEvent], Coroutine[Any, Any, None]]:
        async def _f(e: DOMEvent) -> None:
            e.preventDefault()
            id = cast("str", id_el.value)
            fortune = await self.get_by_id(id)

            if not fortune:
                return

            self.clear_fortunes()
            self.fortunes_content <= create_fortune(fortune)

        return _f

    def callback_submit(
        self,
        content_el: INPUT,
        author_el: INPUT,
    ) -> Callable[[DOMEvent], Coroutine[Any, Any, None]]:
        async def _f(e: DOMEvent) -> None:
            e.preventDefault()
            await self.submit(
                cast("str", content_el.value),
                cast("str | None", author_el.value),
            )

        return _f

    def save(self, _e: DOMEvent) -> None:
        local_storage.storage["api_key"] = json.dumps(self.api_key)

    def restore(self) -> None:
        if not (api_key := local_storage.storage.get("api_key", None)):
            return
        # Could still be "null", check again
        if api_key := json.loads(api_key):
            self.api_key = api_key
            success_dialog("Restored API key from local storage")


def error_dialog(e: _ToString) -> None:
    document <= InfoDialog("Error", str(e), remove_after=2)


def success_dialog(msg: _ToString = "") -> None:
    document <= InfoDialog("OK!", str(msg), remove_after=2)


def create_fortune(fortune: Fortune) -> _HTMLElement:
    return DIV(
        (
            P(fortune.content, Class="fortune-content"),
            P(
                f"Submitted by {fortune.author or 'Anonymous'}",
                CLass="fortune-author",
            ),
            P(
                f"Category: {fortune.category}",
                CLass="fortune-category",
            ),
        ),
        Class="fortune-container",
    )


def make_category_option(category: Category) -> OPTION:
    out = OPTION(category.value.replace("-", " ").title())
    out.attrs["value"] = category.value

    return out


async def main() -> None:
    g = document.getElementById
    state = State(fortunes_content=cast("DIV", g("fortunes-content")))

    state.restore()

    window.bind("beforeunload", state.save)  # pyright: ignore[reportAttributeAccessIssue]

    state.init_registration_button()

    labels = g("category-labels")
    labels <= [make_category_option(category) for category in Category]

    random_button = cast("BUTTON", g("random"))
    random_button.bind("click", lambda e: aio.run(state.callback_random(e)))

    search_form = cast("FORM", g("search-form"))
    search_query = cast("INPUT", g("query"))
    search_limit = cast("INPUT", g("search-limit"))
    search_form.bind(
        "submit",
        lambda e: aio.run(
            state.callback_search(
                search_query,
                search_limit,
            )(e),
        ),
    )

    category_form = cast("FORM", g("category-form"))
    category_el = cast("SELECT", g("category-labels"))
    category_limit = cast("INPUT", g("category-limit"))
    category_form.bind(
        "submit",
        lambda e: aio.run(
            state.callback_category(
                category_el,
                category_limit,
            )(e),
        ),
    )

    id_form = cast("FORM", g("id-form"))
    id_el = cast("INPUT", g("id"))
    id_form.bind(
        "submit",
        lambda e: aio.run(
            state.callback_id(
                id_el,
            )(e),
        ),
    )

    submit_form = cast("FORM", g("submit-form"))
    content_el = cast("INPUT", g("submit-content"))
    author_el = cast("INPUT", g("submit-author"))
    submit_form.bind(
        "submit",
        lambda e: aio.run(
            state.callback_submit(
                content_el,
                author_el,
            )(e),
        ),
    )

    g("before-load-overlay").attrs["hidden"] = True


aio.run(main())
