"""
POI Feature Service for Forecasting

Fetches POI features for use in demand forecasting predictions.
Ensures feature consistency between training and prediction.
"""

import httpx
from typing import Dict, Any, Optional
import structlog

logger = structlog.get_logger()


class POIFeatureService:
    """
    POI feature service for forecasting.

    Fetches POI context from External service to ensure
    prediction uses the same features as training.
    """

    def __init__(self, external_service_url: str = "http://external-service:8000"):
        """
        Initialize POI feature service.

        Args:
            external_service_url: Base URL for external service
        """
        self.external_service_url = external_service_url.rstrip("/")
        self.poi_context_endpoint = f"{self.external_service_url}/poi-context"

    async def get_poi_features(
        self,
        tenant_id: str
    ) -> Dict[str, Any]:
        """
        Get POI features for tenant.

        Args:
            tenant_id: Tenant UUID

        Returns:
            Dictionary with POI features or empty dict if not available
        """
        try:
            async with httpx.AsyncClient(timeout=10.0) as client:
                response = await client.get(
                    f"{self.poi_context_endpoint}/{tenant_id}"
                )

                if response.status_code == 404:
                    logger.warning(
                        "No POI context found for tenant",
                        tenant_id=tenant_id
                    )
                    return {}

                response.raise_for_status()
                data = response.json()
                poi_context = data.get("poi_context", {})
                ml_features = poi_context.get("ml_features", {})

                logger.info(
                    "POI features retrieved for forecasting",
                    tenant_id=tenant_id,
                    feature_count=len(ml_features)
                )

                return ml_features

        except httpx.HTTPError as e:
            logger.error(
                "Failed to fetch POI features for forecasting",
                tenant_id=tenant_id,
                error=str(e)
            )
            return {}
        except Exception as e:
            logger.error(
                "Unexpected error fetching POI features",
                tenant_id=tenant_id,
                error=str(e),
                exc_info=True
            )
            return {}

    async def check_poi_service_health(self) -> bool:
        """
        Check if POI service is accessible.

        Returns:
            True if service is healthy, False otherwise
        """
        try:
            async with httpx.AsyncClient(timeout=5.0) as client:
                response = await client.get(
                    f"{self.poi_context_endpoint}/health"
                )
                return response.status_code == 200
        except Exception as e:
            logger.error(
                "POI service health check failed",
                error=str(e)
            )
            return False
