from __future__ import annotations

from textual.app import App, ComposeResult
from textual.containers import Container
from textual.widgets import Footer, Header

from .models.workflow import WorkflowState
from .screens.login import LoginView
from .screens.wizard import WizardView
from .services.base import ProxmoxService
from .services.factory import ProxmoxServiceFactory
from .settings import AppSettings
from .terminal_compat import build_driver_class


class PveVmSetupApp(App[None]):
    TITLE = "Proxmox VM Setup"
    SUB_TITLE = "Live-access foundation"

    def __init__(
        self,
        settings: AppSettings,
        *,
        service: ProxmoxService | None = None,
    ) -> None:
        super().__init__(driver_class=build_driver_class())
        self.settings = settings
        self.workflow = WorkflowState()
        self.service = service or ProxmoxServiceFactory.create(settings)

    def compose(self) -> ComposeResult:
        yield Header()
        with Container(id="app-body"):
            yield LoginView(self.settings, self.workflow, self.service)
        yield Footer()

    def on_unmount(self) -> None:
        close = getattr(self.service, "close", None)
        if callable(close):
            close()

    async def on_login_view_authenticated(self, _: LoginView.Authenticated) -> None:
        self.query_one(LoginView).remove()
        wizard = WizardView(self.settings, self.workflow, self.service)
        await self.query_one("#app-body", Container).mount(wizard)
        wizard.activate()
