"""
POI Feature Service for Forecasting

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

from typing import Dict, Any, Optional
import structlog

from shared.clients.external_client import ExternalServiceClient

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_client: ExternalServiceClient = None):
        """
        Initialize POI feature service.

        Args:
            external_client: External service client instance (optional)
        """
        if external_client is None:
            from app.core.config import settings
            self.external_client = ExternalServiceClient(settings, "forecasting-service")
        else:
            self.external_client = external_client

    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:
            result = await self.external_client.get_poi_context(tenant_id)

            if result:
                poi_context = result.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
            else:
                logger.warning(
                    "No POI context found for tenant",
                    tenant_id=tenant_id
                )
                return {}

        except Exception as e:
            logger.error(
                "Failed to fetch POI features for forecasting",
                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 through the external client.

        Returns:
            True if service is healthy, False otherwise
        """
        try:
            # Test the external service health by attempting to get POI context for a dummy tenant
            # This will go through the proper authentication and routing
            dummy_context = await self.external_client.get_poi_context("test-tenant")
            # If we can successfully make a request (even if it returns None for missing tenant),
            # it means the service is accessible
            return True
        except Exception as e:
            logger.error(
                "POI service health check failed",
                error=str(e)
            )
            return False
