"""
Orchestrator client for querying AI action context.

Queries the orchestrator service to determine if AI has already
addressed the issue and what actions were taken.
"""

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

logger = structlog.get_logger()


class OrchestratorClient:
    """HTTP client for querying orchestrator service"""

    def __init__(self, base_url: str = "http://orchestrator-service:8000"):
        """
        Initialize orchestrator client.

        Args:
            base_url: Base URL of orchestrator service
        """
        self.base_url = base_url
        self.timeout = 10.0  # 10 second timeout

    async def get_context(
        self,
        tenant_id: str,
        event_type: str,
        metadata: Dict[str, Any]
    ) -> dict:
        """
        Query orchestrator for AI action context.

        Returns dict with:
        - already_addressed: Boolean - did AI handle this?
        - action_type: Type of action taken
        - action_id: ID of the action
        - action_summary: Human-readable summary
        - reasoning: AI reasoning for the action
        - confidence: Confidence score (0-1)
        - estimated_savings_eur: Estimated savings
        - prevented_issue: What issue was prevented
        - created_at: When action was created
        """

        context = {
            "already_addressed": False,
            "confidence": 0.8  # Default confidence
        }

        try:
            # Build query based on event type and metadata
            query_params = self._build_query_params(event_type, metadata)

            async with httpx.AsyncClient(timeout=self.timeout) as client:
                response = await client.get(
                    f"{self.base_url}/api/internal/recent-actions",
                    params={
                        "tenant_id": tenant_id,
                        **query_params
                    },
                    headers={
                        "x-internal-service": "alert-intelligence"
                    }
                )

                if response.status_code == 200:
                    data = response.json()
                    context.update(self._parse_response(data, event_type, metadata))

                elif response.status_code == 404:
                    # No recent actions found - that's okay
                    logger.debug("no_orchestrator_actions", tenant_id=tenant_id, event_type=event_type)

                else:
                    logger.warning(
                        "orchestrator_query_failed",
                        status_code=response.status_code,
                        tenant_id=tenant_id
                    )

        except httpx.TimeoutException:
            logger.warning("orchestrator_timeout", tenant_id=tenant_id, event_type=event_type)

        except Exception as e:
            logger.error("orchestrator_query_error", error=str(e), tenant_id=tenant_id)

        return context

    def _build_query_params(self, event_type: str, metadata: Dict[str, Any]) -> dict:
        """Build query parameters based on event type"""
        params = {}

        # For stock-related alerts, query for PO actions
        if "stock" in event_type or "shortage" in event_type:
            if metadata.get("ingredient_id"):
                params["related_entity_type"] = "ingredient"
                params["related_entity_id"] = metadata["ingredient_id"]
            params["action_types"] = "purchase_order_created,purchase_order_approved"

        # For production delays, query for batch adjustments
        elif "production" in event_type or "delay" in event_type:
            if metadata.get("batch_id"):
                params["related_entity_type"] = "production_batch"
                params["related_entity_id"] = metadata["batch_id"]
            params["action_types"] = "production_adjusted,batch_rescheduled"

        # For PO approval, check if already approved
        elif "po_approval" in event_type:
            if metadata.get("po_id"):
                params["related_entity_type"] = "purchase_order"
                params["related_entity_id"] = metadata["po_id"]
                params["action_types"] = "purchase_order_approved,purchase_order_rejected"

        # Look for recent actions (last 24 hours)
        params["since_hours"] = 24

        return params

    def _parse_response(
        self,
        data: dict,
        event_type: str,
        metadata: Dict[str, Any]
    ) -> dict:
        """Parse orchestrator response into context"""

        if not data or not data.get("actions"):
            return {"already_addressed": False}

        # Get most recent action
        actions = data.get("actions", [])
        if not actions:
            return {"already_addressed": False}

        most_recent = actions[0]

        context = {
            "already_addressed": True,
            "action_type": most_recent.get("action_type"),
            "action_id": most_recent.get("id"),
            "action_summary": most_recent.get("summary", ""),
            "reasoning": most_recent.get("reasoning", {}),
            "confidence": most_recent.get("confidence", 0.8),
            "created_at": most_recent.get("created_at"),
            "action_status": most_recent.get("status", "completed")
        }

        # Extract specific fields based on action type
        if most_recent.get("action_type") == "purchase_order_created":
            context["estimated_savings_eur"] = most_recent.get("estimated_savings_eur", 0)
            context["prevented_issue"] = "stockout"

            if most_recent.get("delivery_date"):
                context["delivery_date"] = most_recent["delivery_date"]

        elif most_recent.get("action_type") == "production_adjusted":
            context["prevented_issue"] = "production_delay"
            context["adjustment_type"] = most_recent.get("adjustment_type")

        return context
