"""Factory for visible vs silent user authentication."""

import asyncio
from typing import Union

from ws_package.entities.user_entity import UserEntity
from ws_package.log.writer import LogWriter
from ws_package.utils.build_mode import apply_org_to_activity, is_silent_build

logger = LogWriter.file(__name__)


def get_user_controller():
    if is_silent_build():
        from ws_package.controllers.user_controller_silent import SilentUserController

        return SilentUserController()

    from ws_package.controllers.user_controller import UserController

    return UserController()


def authenticate_user() -> UserEntity | None:
    """Authenticate using Electron DB (visible) or stealth token login (silent)."""
    silent = is_silent_build()
    logger.info("[Auth] Using %s authentication path", "stealth_login (silent)" if silent else "Electron DB (visible)")
    controller = get_user_controller()
    if silent:
        return asyncio.run(controller.authenticate())
    return controller.authenticate()


async def authenticate_user_async() -> UserEntity | None:
    """Async-safe authenticate for coroutines (wake handler, status refresh)."""
    silent = is_silent_build()
    logger.info(
        "[Auth] Using %s authentication path (async)",
        "stealth_login (silent)" if silent else "Electron DB (visible)",
    )
    controller = get_user_controller()
    if silent:
        return await controller.authenticate()
    return await controller.authenticate_async()


async def get_user_for_wake() -> UserEntity | None:
    """Load user for post-wake status check without re-hitting login APIs.

    Silent mode: read last saved user from Python DB (stealth_login only at startup
    or when status API returns code 1001 and login_call() runs).
    Visible mode: refresh from Electron DB (no stealth_login).
    """
    if is_silent_build():
        from ws_package.controllers.user_controller_silent import SilentUserController

        logger.info("[Auth] Silent wake — using cached user from DB (no stealth_login)")
        return await SilentUserController().get_last_user()

    controller = get_user_controller()
    logger.info("[Auth] Visible wake — refreshing user from Electron DB")
    return await controller.authenticate_async()


def fetch_and_apply_org_settings(user_entity: UserEntity, activity) -> None:
    """Fetch org config from API and apply to activity (silent startup path)."""
    if not is_silent_build():
        return

    from ws_package.controllers.user_controller_silent import SilentUserController

    controller = SilentUserController()

    async def _run():
        return await controller.get_user_org(user_entity)

    try:
        org_entity = asyncio.run(_run())
        apply_org_to_activity(activity, org_entity)
    except Exception as e:
        logger.error("[Silent] Failed to fetch/apply org settings: %s", e, exc_info=True)
