"""
Orchestration Notification Service - Simplified

Emits minimal events using EventPublisher.
All enrichment handled by alert_processor.
"""

from datetime import datetime, timezone
from typing import Optional, Dict, Any
from uuid import UUID
import structlog

from shared.messaging import UnifiedEventPublisher

logger = structlog.get_logger()


class OrchestrationNotificationService:
    """
    Service for emitting orchestration notifications using EventPublisher.
    """

    def __init__(self, event_publisher: UnifiedEventPublisher):
        self.publisher = event_publisher

    async def emit_orchestration_run_started_notification(
        self,
        tenant_id: UUID,
        run_id: str,
        run_type: str,  # 'scheduled', 'manual', 'triggered'
        scope: str,  # 'full', 'inventory_only', 'production_only'
    ) -> None:
        """
        Emit notification when an orchestration run starts.
        """
        metadata = {
            "run_id": run_id,
            "run_type": run_type,
            "scope": scope,
            "started_at": datetime.now(timezone.utc).isoformat(),
        }

        await self.publisher.publish_notification(
            event_type="operations.orchestration_run_started",
            tenant_id=tenant_id,
            data=metadata
        )

        logger.info(
            "orchestration_run_started_notification_emitted",
            tenant_id=str(tenant_id),
            run_id=run_id
        )

    async def emit_orchestration_run_completed_notification(
        self,
        tenant_id: UUID,
        run_id: str,
        duration_seconds: float,
        actions_created: int,
        actions_by_type: Dict[str, int],  # e.g., {'purchase_order': 2, 'production_batch': 3}
        status: str = "success",
    ) -> None:
        """
        Emit notification when an orchestration run completes.
        """
        # Build message with action summary
        if actions_created == 0:
            action_summary = "No actions needed"
        else:
            action_summary = ", ".join([f"{count} {action_type}" for action_type, count in actions_by_type.items()])

        metadata = {
            "run_id": run_id,
            "status": status,
            "duration_seconds": float(duration_seconds),
            "actions_created": actions_created,
            "actions_by_type": actions_by_type,
            "action_summary": action_summary,
            "completed_at": datetime.now(timezone.utc).isoformat(),
        }

        await self.publisher.publish_notification(
            event_type="operations.orchestration_run_completed",
            tenant_id=tenant_id,
            data=metadata
        )

        logger.info(
            "orchestration_run_completed_notification_emitted",
            tenant_id=str(tenant_id),
            run_id=run_id,
            actions_created=actions_created
        )

    async def emit_action_created_notification(
        self,
        tenant_id: UUID,
        run_id: str,
        action_id: str,
        action_type: str,  # 'purchase_order', 'production_batch', 'inventory_adjustment'
        action_details: Dict[str, Any],  # Type-specific details
        reason: str,
        estimated_impact: Optional[Dict[str, Any]] = None,
    ) -> None:
        """
        Emit notification when the orchestrator creates an action.
        """
        metadata = {
            "run_id": run_id,
            "action_id": action_id,
            "action_type": action_type,
            "action_details": action_details,
            "reason": reason,
            "estimated_impact": estimated_impact,
            "created_at": datetime.now(timezone.utc).isoformat(),
        }

        await self.publisher.publish_notification(
            event_type="operations.action_created",
            tenant_id=tenant_id,
            data=metadata
        )

        logger.info(
            "action_created_notification_emitted",
            tenant_id=str(tenant_id),
            action_id=action_id,
            action_type=action_type
        )

    async def emit_action_completed_notification(
        self,
        tenant_id: UUID,
        action_id: str,
        action_type: str,
        action_status: str,  # 'approved', 'completed', 'rejected', 'cancelled'
        completed_by: Optional[str] = None,
    ) -> None:
        """
        Emit notification when an orchestrator action is completed/resolved.
        """
        metadata = {
            "action_id": action_id,
            "action_type": action_type,
            "action_status": action_status,
            "completed_by": completed_by,
            "completed_at": datetime.now(timezone.utc).isoformat(),
        }

        await self.publisher.publish_notification(
            event_type="operations.action_completed",
            tenant_id=tenant_id,
            data=metadata
        )

        logger.info(
            "action_completed_notification_emitted",
            tenant_id=str(tenant_id),
            action_id=action_id,
            action_status=action_status
        )