from fastapi import APIRouter, Request
from fastapi.responses import FileResponse

from app.core.config import get_settings
from app.core.exceptions import AppError
from app.schemas.mobile_release import MobileReleaseInfo
from app.services.mobile_release_service import get_mobile_release_apk_path, get_mobile_release_info

router = APIRouter()


def _request_base_url(request: Request) -> str:
    forwarded_proto = request.headers.get("x-forwarded-proto")
    scheme = forwarded_proto.split(",")[0].strip() if forwarded_proto else request.url.scheme
    host = request.headers.get("x-forwarded-host") or request.headers.get("host") or request.url.netloc
    return f"{scheme}://{host}"


@router.get("/mobile-release", response_model=MobileReleaseInfo)
def mobile_release_check(request: Request):
    """Return the latest sideload APK metadata for the mobile app."""
    settings = get_settings()
    info = get_mobile_release_info(settings, _request_base_url(request))
    if not info:
        raise AppError(
            "No mobile app release is published on this server yet",
            code="MOBILE_RELEASE_NOT_CONFIGURED",
            status_code=404,
        )
    return info


@router.get("/mobile-release/download")
def mobile_release_download():
    """Download the published Android APK (sideload updates outside Play Store)."""
    settings = get_settings()
    if not settings.mobile_release_enabled:
        raise AppError(
            "Mobile release downloads are disabled on this server",
            code="MOBILE_RELEASE_NOT_CONFIGURED",
            status_code=404,
        )
    apk_path = get_mobile_release_apk_path(settings)
    return FileResponse(
        apk_path,
        media_type="application/vnd.android.package-archive",
        filename=apk_path.name,
    )
