from fastapi import APIRouter, Depends, HTTPException, Query, Request, status from pydantic import BaseModel, Field from sqlalchemy.ext.asyncio import AsyncSession from uuid import UUID from app.core.access_gate import ( EarthAccessContext, check_sliding_rate_limit, require_earth_or_api_access, ) from app.db.session import get_db from app.services.earth_news import ( ALLOWED_NEWS_CATEGORY_KEYS, SUPPORTED_NEWS_LOCALES, REGION_ANCHORS, determine_focus_region, get_earth_news_payload, ) router = APIRouter() class EarthNewsRefreshRequest(BaseModel): lat: float | None = Field(default=None, ge=-90, le=90) lon: float | None = Field(default=None, ge=-180, le=180) region: str | None = Field(default=None, max_length=64) def _parse_categories(raw: str | None) -> set[str] | None: if raw is None or not raw.strip(): return None requested = {item.strip().lower() for item in raw.split(",") if item.strip()} invalid = sorted(requested - set(ALLOWED_NEWS_CATEGORY_KEYS)) if invalid: raise HTTPException( status_code=422, detail={ "message": "Unsupported news categories.", "invalid_categories": invalid, "allowed_categories": list(ALLOWED_NEWS_CATEGORY_KEYS), }, ) return requested or None def _parse_source_ids(raw: str | None) -> set[str] | None: if raw is None or not raw.strip(): return None return {item.strip() for item in raw.split(",") if item.strip()} or None def _parse_limit(raw: int | None) -> int: if raw is None: return 12 if raw < 1: raise HTTPException( status_code=422, detail={"message": "News limit must be greater than 0."} ) return min(raw, 100) def _parse_locale(raw: str | None) -> str: if raw is None or not raw.strip(): return "zh-CN" requested = raw.strip() if requested not in SUPPORTED_NEWS_LOCALES: raise HTTPException( status_code=422, detail={ "message": "Unsupported news locale.", "invalid_locale": requested, "allowed_locales": sorted(SUPPORTED_NEWS_LOCALES), }, ) return requested async def _require_news_refresh_cooldown( request: Request, access: EarthAccessContext = Depends(require_earth_or_api_access("news:read")), ) -> None: peer = request.client.host if (request.client and request.client.host) else "unknown" await check_sliding_rate_limit( f"news_refresh:{access.actor_key}:{peer}", limit=3, window_seconds=60, detail="News refresh cooldown active; please retry shortly.", ) @router.post( "/refresh", status_code=status.HTTP_202_ACCEPTED, dependencies=[Depends(_require_news_refresh_cooldown)], ) async def request_earth_news_refresh(payload: EarthNewsRefreshRequest): requested_region = payload.region.strip().lower() if payload.region else None if requested_region and requested_region not in REGION_ANCHORS: raise HTTPException( status_code=422, detail={ "message": "Unsupported news region.", "invalid_region": requested_region, "allowed_regions": list(REGION_ANCHORS.keys()), }, ) region = requested_region or determine_focus_region(payload.lat, payload.lon) from app.services.scheduler import request_earth_news_region_refresh try: return request_earth_news_region_refresh(region) except Exception as exc: raise HTTPException( status_code=503, detail={ "code": "refresh_failed", "message": "Could not start a news refresh. Please try again.", }, ) from exc @router.get( "/refresh/{refresh_id}", dependencies=[Depends(require_earth_or_api_access("news:read"))], ) async def get_earth_news_refresh(refresh_id: UUID): from app.services.earth_news_refresh import get_earth_news_refresh_status try: result = get_earth_news_refresh_status(refresh_id.hex) except Exception as exc: raise HTTPException( status_code=503, detail={ "code": "refresh_failed", "message": "Refresh status is temporarily unavailable. Please retry.", }, ) from exc if result is not None: return result return { "refresh_id": refresh_id.hex, "region": None, "status": "failed", "error": { "code": "expired", "message": "Refresh status expired. Submit a new refresh.", }, } @router.get( "/earth-feed", dependencies=[Depends(require_earth_or_api_access("news:read"))], ) async def get_earth_feed( lat: float | None = Query(None, description="Current Earth view center latitude"), lon: float | None = Query(None, description="Current Earth view center longitude"), region: str | None = Query( None, description="Explicit Earth news region for UE/client integrations" ), categories: str | None = Query(None, description="Comma-separated news category keys"), sources: str | None = Query(None, description="Comma-separated news source ids"), limit: int | None = Query(None, description="Maximum news items to return, capped at 100"), locale: str | None = Query(None, description="Display locale, zh-CN or en-US"), db: AsyncSession = Depends(get_db), ): normalized_region = ( region.strip().lower() if isinstance(region, str) and region.strip() else None ) if normalized_region is not None and normalized_region not in REGION_ANCHORS: raise HTTPException( status_code=422, detail={ "message": "Unsupported news region.", "invalid_region": normalized_region, "allowed_regions": list(REGION_ANCHORS.keys()), }, ) return await get_earth_news_payload( lat=lat, lon=lon, region=normalized_region, categories=_parse_categories(categories), source_ids=_parse_source_ids(sources), limit=_parse_limit(limit), locale=_parse_locale(locale), db=db, )