"""
Signals Gateway Tools for Meta Ads MCP Server

This module provides tools for working with Meta's Signals Gateway,
a server-side solution for routing conversion events to Meta.

Based on Meta Marketing API:
https://developers.facebook.com/docs/marketing-api/gateway-products/signals-gateway
"""

from __future__ import annotations

from typing import Dict, Any, Optional

from .errors import MetaApiError
from .logging import get_logger
from .meta_client import MetaClient
from .schemas import ToolResult

logger = get_logger(__name__)


class SignalsGatewayEngine:
    """Handles Signals Gateway operations"""
    
    def __init__(self, client: MetaClient):
        self.client = client
    
    async def get_gateway_instances(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Get all Signals Gateway instances for a business.
        
        Args:
            arguments: {
                "business_id": "123"
            }
        
        Returns:
            ToolResult with gateway instances
        """
        try:
            business_id = arguments.get("business_id")
            
            if not business_id:
                return ToolResult(
                    ok=False,
                    error={"message": "business_id is required"}
                )
            
            logger.info(f"Getting Signals Gateway instances for business: {business_id}")
            
            response = await self.client.get(
                f"{business_id}/signal_gateway_instances",
                params={"fields": "id,name,status,pixel_id,domain"}
            )
            
            instances = response.get("data", [])
            
            return ToolResult(
                ok=True,
                data={
                    "business_id": business_id,
                    "gateway_instances": instances,
                    "count": len(instances),
                    "about_signals_gateway": {
                        "description": "Server-side event routing infrastructure",
                        "benefits": [
                            "Higher event match quality",
                            "Bypass browser restrictions",
                            "Multi-domain support",
                            "Cloud-hosted solution"
                        ],
                        "supported_clouds": ["AWS", "GCP", "Azure"]
                    }
                }
            )
            
        except MetaApiError as exc:
            logger.error("get_gateway_instances_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"get_gateway_instances_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def get_gateway_health(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Check health status of a Signals Gateway instance.
        
        Args:
            arguments: {
                "gateway_id": "123"
            }
        
        Returns:
            ToolResult with health status
        """
        try:
            gateway_id = arguments.get("gateway_id")
            
            if not gateway_id:
                return ToolResult(
                    ok=False,
                    error={"message": "gateway_id is required"}
                )
            
            logger.info(f"Checking Signals Gateway health: {gateway_id}")
            
            response = await self.client.get(
                gateway_id,
                params={
                    "fields": "id,name,status,last_event_time,events_received_today,event_match_quality"
                }
            )
            
            status = response.get("status", "UNKNOWN")
            
            return ToolResult(
                ok=True,
                data={
                    "gateway_id": gateway_id,
                    "name": response.get("name"),
                    "status": status,
                    "is_healthy": status == "ACTIVE",
                    "last_event_time": response.get("last_event_time"),
                    "events_received_today": response.get("events_received_today", 0),
                    "event_match_quality": response.get("event_match_quality"),
                    "recommendations": (
                        ["Gateway is operating normally"] 
                        if status == "ACTIVE" 
                        else ["Check gateway configuration", "Verify cloud deployment", "Review event routing"]
                    )
                }
            )
            
        except MetaApiError as exc:
            logger.error("get_gateway_health_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"get_gateway_health_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def get_gateway_diagnostics(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Get detailed diagnostics for a Signals Gateway.
        
        Args:
            arguments: {
                "gateway_id": "123",
                "time_range": {"since": "2024-01-01", "until": "2024-01-31"}
            }
        
        Returns:
            ToolResult with diagnostic data
        """
        try:
            gateway_id = arguments.get("gateway_id")
            
            if not gateway_id:
                return ToolResult(
                    ok=False,
                    error={"message": "gateway_id is required"}
                )
            
            logger.info(f"Getting Signals Gateway diagnostics: {gateway_id}")
            
            params = {
                "fields": ",".join([
                    "id",
                    "events_dropped",
                    "events_received",
                    "events_processed",
                    "avg_latency_ms",
                    "error_rate"
                ])
            }
            
            if "time_range" in arguments:
                params["time_range"] = arguments["time_range"]
            
            response = await self.client.get(
                f"{gateway_id}/diagnostics",
                params=params
            )
            
            return ToolResult(
                ok=True,
                data={
                    "gateway_id": gateway_id,
                    "diagnostics": response,
                    "health_indicators": {
                        "event_processing": {
                            "received": response.get("events_received", 0),
                            "processed": response.get("events_processed", 0),
                            "dropped": response.get("events_dropped", 0)
                        },
                        "performance": {
                            "avg_latency_ms": response.get("avg_latency_ms"),
                            "error_rate": response.get("error_rate")
                        }
                    }
                }
            )
            
        except MetaApiError as exc:
            logger.error("get_gateway_diagnostics_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"get_gateway_diagnostics_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})


_signals_gateway_engine: Optional[SignalsGatewayEngine] = None


def get_signals_gateway_engine() -> SignalsGatewayEngine:
    """Get the global SignalsGatewayEngine instance"""
    global _signals_gateway_engine
    if _signals_gateway_engine is None:
        from .meta_client import get_client
        _signals_gateway_engine = SignalsGatewayEngine(get_client())
    return _signals_gateway_engine
