from __future__ import annotations

from textual.app import App

from termchat.api import ApiClient
from termchat.config import CONFIG_DIR
from termchat.themes import DEFAULT_THEME, THEMES


class TermChatApp(App):
    CSS_PATH = "termchat.tcss"
    TITLE = "termchat"

    def __init__(self) -> None:
        super().__init__()
        self.api = ApiClient()

    def on_ready(self) -> None:
        for t in THEMES:
            self.register_theme(t)

        theme_file = CONFIG_DIR / "theme"
        if theme_file.exists():
            saved = theme_file.read_text().strip()
            theme_names = [t.name for t in THEMES]
            if saved in theme_names:
                self.theme = saved
                return
        self.theme = DEFAULT_THEME

    async def on_mount(self) -> None:
        from termchat.auth import load_tokens

        tokens = load_tokens()
        if tokens:
            # Push chat screen immediately — it handles loading data itself
            from termchat.screens.chat import ChatScreen
            self.push_screen(ChatScreen())
            # Check for updates in background
            import asyncio
            asyncio.create_task(self._check_update())
            return

        from termchat.screens.login import LoginScreen
        self.push_screen(LoginScreen())

    async def _check_update(self) -> None:
        """Check PyPI for newer version."""
        try:
            import importlib.metadata
            current = importlib.metadata.version("trmchat")
            resp = await self.api._client.get("https://pypi.org/pypi/trmchat/json", timeout=3.0)
            if resp.status_code == 200:
                latest = resp.json()["info"]["version"]
                if latest != current:
                    if self.screen:
                        self.screen.notify(
                            f"update available: v{current} \u2192 v{latest}\npip install --upgrade trmchat",
                            timeout=6,
                        )
        except Exception:
            pass

    async def on_unmount(self) -> None:
        try:
            await self.api.close()
        except Exception:
            pass


def main() -> None:
    app = TermChatApp()
    app.run()


if __name__ == "__main__":
    main()
