"""Android entry point for LedGrab.

Called from Kotlin via Chaquopy to start/stop the FastAPI server
inside an Android application.  Sets up Android-specific paths
(app-private storage) before importing the main application.
"""

import asyncio
import os
import threading
from typing import Any, Optional

_server_thread: Optional[threading.Thread] = None
_server: Optional[Any] = None  # uvicorn.Server
_loop: Optional[asyncio.AbstractEventLoop] = None


def start_server(data_dir: str, port: int = 8080) -> None:
    """Start the LedGrab uvicorn server.

    Called from Kotlin's ``PythonBridge.startServer()``.  This function
    blocks until ``stop_server()`` is called, so Kotlin should invoke it
    on a background thread.

    Args:
        data_dir: Android app-private files directory
                  (e.g. ``/data/data/com.ledgrab.android/files``).
        port: HTTP port for the web UI / API.
    """
    # ── Configure paths before any LedGrab imports ──────────────
    os.makedirs(os.path.join(data_dir, "data"), exist_ok=True)
    os.makedirs(os.path.join(data_dir, "data", "assets"), exist_ok=True)
    os.makedirs(os.path.join(data_dir, "config"), exist_ok=True)

    # Change working directory to app-private storage so relative
    # paths (e.g. "config/default_config.yaml") don't hit system dirs
    os.chdir(data_dir)

    os.environ["LEDGRAB_STORAGE__DATABASE_FILE"] = os.path.join(data_dir, "data", "ledgrab.db")
    os.environ["LEDGRAB_ASSETS__ASSETS_DIR"] = os.path.join(data_dir, "data", "assets")
    os.environ["LEDGRAB_SERVER__HOST"] = "0.0.0.0"
    os.environ["LEDGRAB_SERVER__PORT"] = str(port)

    # ── Now safe to import LedGrab ──────────────────────────────
    import uvicorn  # noqa: E402

    from ledgrab.utils import setup_logging, get_logger  # noqa: E402

    setup_logging()
    logger = get_logger(__name__)
    logger.info("LedGrab Android: starting server on port %d", port)
    logger.info("Data directory: %s", data_dir)

    from ledgrab.config import get_config  # noqa: E402

    config = get_config()

    uv_config = uvicorn.Config(
        "ledgrab.main:app",
        host=config.server.host,
        port=port,
        log_level=config.server.log_level.lower(),
        # No uvloop/httptools on Android — use pure-Python asyncio
        loop="asyncio",
    )

    global _server, _loop
    _server = uvicorn.Server(uv_config)
    _loop = asyncio.new_event_loop()
    asyncio.set_event_loop(_loop)

    logger.info("LedGrab Android: server starting")
    _loop.run_until_complete(_server.serve())
    logger.info("LedGrab Android: server stopped")

    # Clean up so the next start_server() call begins fresh.
    _server = None
    _loop = None


def stop_server() -> None:
    """Signal the uvicorn server to shut down gracefully.

    Called from Kotlin's ``PythonBridge.stopServer()``.  Sets
    ``should_exit`` on the uvicorn Server which causes ``server.serve()``
    to return, unblocking the Python thread.
    """
    if _server is not None:
        _server.should_exit = True
