"""
Knock Notification Service.

Handles sending notifications via Knock for execution sharing and access control.
"""

import os
from typing import Optional
import structlog

logger = structlog.get_logger()


class KnockService:
    """Service for sending notifications via Knock"""

    def __init__(self):
        self.api_key = os.getenv("KNOCK_API_KEY")
        if not self.api_key:
            logger.warning("KNOCK_API_KEY not set - notifications disabled")
            self.client = None
        else:
            try:
                from knockapi import Knock
                self.client = Knock(api_key=self.api_key)
                logger.info("Knock client initialized successfully")
            except ImportError:
                logger.warning("knockapi package not installed - notifications disabled")
                self.client = None

    async def send_access_request_notification(
        self,
        execution_id: str,
        execution_name: str,
        requester_id: str,
        requester_name: str,
        requester_email: str,
        owner_id: str,
        owner_email: str,
    ) -> bool:
        """Notify execution owner of access request"""
        if not self.client:
            logger.warning("Knock client not initialized - skipping notification")
            return False

        try:
            self.client.workflows.trigger(
                workflow="access-request-received",
                recipients=[{"id": owner_id, "email": owner_email}],
                data={
                    "execution_id": execution_id,
                    "execution_name": execution_name,
                    "requester_id": requester_id,
                    "requester_name": requester_name,
                    "requester_email": requester_email,
                    "action_url": f"/executions/{execution_id}/access-requests",
                }
            )
            logger.info(
                "Sent access request notification",
                owner_email=owner_email,
                requester_email=requester_email,
            )
            return True
        except Exception as e:
            logger.error("Failed to send Knock notification", error=str(e))
            return False

    async def send_access_granted_notification(
        self,
        execution_id: str,
        execution_name: str,
        granted_user_id: str,
        granted_user_email: str,
    ) -> bool:
        """Notify user their access request was granted"""
        if not self.client:
            return False

        try:
            self.client.workflows.trigger(
                workflow="access-granted",
                recipients=[{"id": granted_user_id, "email": granted_user_email}],
                data={
                    "execution_id": execution_id,
                    "execution_name": execution_name,
                    "view_url": f"/executions/{execution_id}",
                }
            )
            logger.info(
                "Sent access granted notification",
                user_email=granted_user_email,
            )
            return True
        except Exception as e:
            logger.error("Failed to send Knock notification", error=str(e))
            return False

    async def send_access_denied_notification(
        self,
        execution_id: str,
        denied_user_id: str,
        denied_user_email: str,
        reason: Optional[str] = None,
    ) -> bool:
        """Notify user their access request was denied"""
        if not self.client:
            return False

        try:
            self.client.workflows.trigger(
                workflow="access-denied",
                recipients=[{"id": denied_user_id, "email": denied_user_email}],
                data={
                    "execution_id": execution_id,
                    "reason": reason or "The owner declined your access request.",
                }
            )
            logger.info(
                "Sent access denied notification",
                user_email=denied_user_email,
            )
            return True
        except Exception as e:
            logger.error("Failed to send Knock notification", error=str(e))
            return False


# Singleton instance
knock_service = KnockService()
