import os

from fastapi import FastAPI

from .static_files import SPAStaticFiles


def mount_spa(app: FastAPI, build_dir: str, api_prefix: str = "api/"):
    """
    Mounts a Single Page Application (SPA) to the FastAPI app using ASGI StaticFiles.

    Args:
        app: The FastAPI application instance.
        build_dir: The directory containing the built frontend files (dist).
        api_prefix: The prefix for API routes to exclude from SPA fallback.
    """
    # Check if build_dir exists to avoid startup errors
    if not os.path.isdir(build_dir):
        print(
            f"Warning: SPA build directory '{build_dir}' does not exist. SPA will not be served."
        )
        return

    app.mount(
        "/", SPAStaticFiles(directory=build_dir, api_prefix=api_prefix), name="spa"
    )
