# Copyright 2025 Softwell S.r.l.
# Licensed under the Apache License, Version 2.0

"""Login Page - HTML form for session-based user authentication.

Mountable as sys_app via config:
    sys_apps:
      login_page:
        module: "genro_asgi.sys_applications.login_page.login_page_app:Application"

Endpoints:
    /: Login page with HTML form.
    /settings: JSON with client-side configuration (cookie name, redirect, etc.).
"""

from __future__ import annotations

from pathlib import Path
from typing import Any, ClassVar

from genro_routes import route  # type: ignore[import-untyped]

from genro_asgi import AsgiApplication

__all__ = ["Application"]

RESOURCES_DIR = Path(__file__).parent / "resources"


class Application(AsgiApplication):
    """Login page sys_app. Serves an HTML form that authenticates via /_server/login."""

    openapi_info: ClassVar[dict[str, Any]] = {
        "title": "Login Page",
        "version": "1.0.0",
        "description": "HTML login form for session-based authentication.",
    }

    def on_init(self, **kwargs: Any) -> None:
        """Initialize with configurable cookie and redirect settings.

        Args:
            **kwargs: Config parameters from YAML:
                cookie_name: Session cookie name (default "session_id").
                cookie_path: Cookie path (default "/").
                redirect_to: URL after successful login (default "/").
                login_endpoint: Server login API URL (default "/_server/login").
        """
        self._cookie_name: str = kwargs.get("cookie_name", "session_id")
        self._cookie_path: str = kwargs.get("cookie_path", "/")
        self._redirect_to: str = kwargs.get("redirect_to", "/")
        self._login_endpoint: str = kwargs.get("login_endpoint", "/_server/login")

    @route(meta_mime_type="text/html")
    def index(self) -> str:
        """Serve the login page."""
        html_path = RESOURCES_DIR / "index.html"
        return html_path.read_text()

    @route()
    def settings(self) -> dict[str, str]:
        """Return client-side configuration for the login form JS.

        Returns:
            Dict with login_endpoint, cookie_name, cookie_path, redirect_to.
        """
        return {
            "login_endpoint": self._login_endpoint,
            "cookie_name": self._cookie_name,
            "cookie_path": self._cookie_path,
            "redirect_to": self._redirect_to,
        }


if __name__ == "__main__":
    pass
