"""API entrypoint for Vercel deployment.

The wrapper exists to add ``/ads.txt`` and an explicit failure-mode
fallback that returns 503 when the real ``app.main`` import collapses
(e.g. missing native dep on a cold serverless container). The real
FastAPI app is mounted at ``/`` so every route resolves underneath
the wrapper.

Caveat closed by L2 finding #26: ``wrapper.mount("/", _app)`` makes
``wrapper.openapi()`` return an empty schema because mounted sub-apps
contribute zero routes to the parent OpenAPI document. To keep the
documented ``/openapi.json`` and ``/docs`` URLs useful in the deployed
environment we explicitly proxy both endpoints to the inner app's
real schema.
"""

from __future__ import annotations

import logging
import sys
from pathlib import Path

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse, PlainTextResponse


ADS_TXT = "google.com, pub-4776839434801841, DIRECT, f08c47fec0942fa0\n"

_HERE = Path(__file__).resolve()
for _candidate in (_HERE.parent, _HERE.parent.parent):
    if (_candidate / "app").is_dir() and str(_candidate) not in sys.path:
        sys.path.insert(0, str(_candidate))

try:
    from app.main import app as _app  # type: ignore[import-not-found]
except Exception:
    try:
        from backend.app.main import app as _app
    except Exception:
        _app = None
        logging.getLogger("backend.index").exception("API application failed to import")

# ``docs_url``/``redoc_url``/``openapi_url`` are explicitly disabled on
# the wrapper so we can serve the inner app's schema on the documented
# paths without FastAPI complaining about duplicate route registration.
wrapper = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)


@wrapper.get("/ads.txt", include_in_schema=False)
@wrapper.head("/ads.txt", include_in_schema=False)
def ads_txt() -> PlainTextResponse:
    return PlainTextResponse(
        ADS_TXT,
        headers={"cache-control": "public, max-age=0, must-revalidate"},
    )


if _app is not None:

    @wrapper.get("/openapi.json", include_in_schema=False)
    def proxied_openapi() -> JSONResponse:
        """Surface the inner app's OpenAPI schema at the canonical URL.

        Without this proxy the wrapper's ``/openapi.json`` returns an
        empty document because ``mount`` does not contribute the inner
        app's routes to the parent's route table — every deployed API
        path would be missing from the published spec.
        """
        return JSONResponse(_app.openapi())

    @wrapper.get("/docs", include_in_schema=False)
    def proxied_docs(request: Request) -> JSONResponse:
        # Lazy import keeps the swagger asset surface optional for cold
        # serverless boots that don't actually serve ``/docs``.
        from fastapi.openapi.docs import get_swagger_ui_html

        return get_swagger_ui_html(
            openapi_url="/openapi.json",
            title=f"{_app.title} — API docs",
        )

    @wrapper.get("/redoc", include_in_schema=False)
    def proxied_redoc(request: Request) -> JSONResponse:
        from fastapi.openapi.docs import get_redoc_html

        return get_redoc_html(
            openapi_url="/openapi.json",
            title=f"{_app.title} — API reference",
        )

    wrapper.mount("/", _app)
else:

    @wrapper.api_route(
        "/{path:path}",
        methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
    )
    def unavailable(path: str) -> None:
        raise HTTPException(status_code=503, detail="API application failed to start")

app = wrapper
application = wrapper
handler = wrapper

__all__ = ["app", "application", "handler"]
