"""
Kafka prompts module for FastMCP.

This module defines prompts and templates for common Kafka operations.
"""

import json
from typing import Dict, List, Any, Optional


class MessageProcessorPrompt:
    """Prompt template for message processing."""

    @staticmethod
    def create_message_template(topic: str, value: str, key: Optional[str] = None,
                             headers: Optional[Dict[str, str]] = None) -> str:
        """
        Create a message processing template.

        Args:
            topic: Kafka topic name
            value: Message value
            key: Message key (optional)
            headers: Message headers (optional)

        Returns:
            Formatted message template string
        """
        template = {
            "topic": topic,
            "value": value,
            "key": key,
            "headers": headers or {}
        }
        return json.dumps(template, indent=2)

    @staticmethod
    def create_batch_message_template(messages: List[Dict[str, Any]]) -> str:
        """
        Create a batch message processing template.

        Args:
            messages: List of message dictionaries

        Returns:
            Formatted batch message template string
        """
        template = {
            "batch": messages,
            "count": len(messages),
            "description": "Batch of messages to be sent to Kafka topics"
        }
        return json.dumps(template, indent=2)

    @staticmethod
    def create_processing_instructions(
        description: str,
        expected_output: str,
        error_handling: str = "continue"
    ) -> str:
        """
        Create message processing instructions.

        Args:
            description: Description of what the processor should do
            expected_output: Description of expected output format
            error_handling: Error handling strategy ("continue", "stop", "skip")

        Returns:
            Formatted instructions string
        """
        instructions = {
            "description": description,
            "expected_output": expected_output,
            "error_handling": error_handling,
            "format": "json"
        }
        return json.dumps(instructions, indent=2)


class ErrorHandlerPrompt:
    """Prompt template for error handling."""

    @staticmethod
    def create_error_template(
        error_type: str,
        error_message: str,
        context: Optional[Dict[str, Any]] = None
    ) -> str:
        """
        Create an error handling template.

        Args:
            error_type: Type of error (e.g., "producer_error", "consumer_error")
            error_message: Error message
            context: Additional context about the error

        Returns:
            Formatted error template string
        """
        template = {
            "error_type": error_type,
            "error_message": error_message,
            "context": context or {},
            "timestamp": "2026-02-02T00:00:00Z",  # Should be actual timestamp
            "severity": "error"
        }
        return json.dumps(template, indent=2)

    @staticmethod
    def create_recovery_plan(error_type: str, suggested_actions: List[str]) -> str:
        """
        Create a recovery plan template.

        Args:
            error_type: Type of error
            suggested_actions: List of suggested recovery actions

        Returns:
            Formatted recovery plan string
        """
        plan = {
            "error_type": error_type,
            "recovery_actions": suggested_actions,
            "priority": "high",
            "estimated_time": "unknown"
        }
        return json.dumps(plan, indent=2)

    @staticmethod
    def create_error_notification(
        error_details: Dict[str, Any],
        notification_type: str = "alert",
        recipients: Optional[List[str]] = None
    ) -> str:
        """
        Create an error notification template.

        Args:
            error_details: Dictionary with error details
            notification_type: Type of notification ("alert", "warning", "info")
            recipients: List of recipient emails/IDs

        Returns:
            Formatted notification string
        """
        notification = {
            "type": notification_type,
            "error_details": error_details,
            "recipients": recipients or [],
            "timestamp": "2026-02-02T00:00:00Z"  # Should be actual timestamp
        }
        return json.dumps(notification, indent=2)


class ConfigurationPrompt:
    """Prompt template for Kafka configuration."""

    @staticmethod
    def create_producer_config_template(
        bootstrap_servers: str,
        acks: str = "all",
        retries: int = 3,
        batch_size: int = 16384
    ) -> str:
        """
        Create a producer configuration template.

        Args:
            bootstrap_servers: Kafka bootstrap servers
            acks: Producer acknowledgment level
            retries: Number of retry attempts
            batch_size: Message batch size

        Returns:
            Formatted configuration template string
        """
        config = {
            "type": "producer",
            "bootstrap_servers": bootstrap_servers,
            "acks": acks,
            "retries": retries,
            "batch_size": batch_size,
            "compression_type": "none",
            "linger_ms": 5,
            "buffer_memory": 33554432
        }
        return json.dumps(config, indent=2)

    @staticmethod
    def create_consumer_config_template(
        bootstrap_servers: str,
        group_id: str = "mcp-consumer",
        auto_offset_reset: str = "earliest",
        enable_auto_commit: bool = True
    ) -> str:
        """
        Create a consumer configuration template.

        Args:
            bootstrap_servers: Kafka bootstrap servers
            group_id: Consumer group ID
            auto_offset_reset: Offset reset policy
            enable_auto_commit: Whether to auto-commit offsets

        Returns:
            Formatted configuration template string
        """
        config = {
            "type": "consumer",
            "bootstrap_servers": bootstrap_servers,
            "group_id": group_id,
            "auto_offset_reset": auto_offset_reset,
            "enable_auto_commit": enable_auto_commit,
            "auto_commit_interval_ms": 1000,
            "session_timeout_ms": 30000,
            "heartbeat_interval_ms": 3000,
            "max_poll_records": 500
        }
        return json.dumps(config, indent=2)

    @staticmethod
    def create_topic_config_template(
        topic_name: str,
        partitions: int = 3,
        replication_factor: int = 1
    ) -> str:
        """
        Create a topic configuration template.

        Args:
            topic_name: Topic name
            partitions: Number of partitions
            replication_factor: Replication factor

        Returns:
            Formatted configuration template string
        """
        config = {
            "topic_name": topic_name,
            "partitions": partitions,
            "replication_factor": replication_factor,
            "configs": {
                "cleanup.policy": "delete",
                "retention.ms": "604800000",  # 7 days
                "segment.ms": "86400000"      # 1 day
            }
        }
        return json.dumps(config, indent=2)


class MonitoringPrompt:
    """Prompt template for monitoring and logging."""

    @staticmethod
    def create_monitoring_template(
        metrics: List[str],
        thresholds: Dict[str, Any],
        time_window: str = "1h"
    ) -> str:
        """
        Create a monitoring template.

        Args:
            metrics: List of metrics to monitor
            thresholds: Dictionary of threshold values
            time_window: Time window for monitoring (e.g., "1h", "5m")

        Returns:
            Formatted monitoring template string
        """
        template = {
            "metrics": metrics,
            "thresholds": thresholds,
            "time_window": time_window,
            "alert_threshold": "exceeds",
            "evaluation_frequency": "1m"
        }
        return json.dumps(template, indent=2)

    @staticmethod
    def create_log_template(
        level: str,
        message: str,
        context: Optional[Dict[str, Any]] = None
    ) -> str:
        """
        Create a logging template.

        Args:
            level: Log level ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL")
            message: Log message
            context: Additional context

        Returns:
            Formatted log template string
        """
        log_entry = {
            "level": level,
            "message": message,
            "context": context or {},
            "timestamp": "2026-02-02T00:00:00Z"  # Should be actual timestamp
        }
        return json.dumps(log_entry, indent=2)

    @staticmethod
    def create_performance_metrics_template(
        operation: str,
        duration: float,
        success: bool,
        error_message: Optional[str] = None
    ) -> str:
        """
        Create performance metrics template.

        Args:
            operation: Operation type (e.g., "send", "consume", "create_topic")
            duration: Operation duration in seconds
            success: Whether operation succeeded
            error_message: Error message if operation failed

        Returns:
            Formatted performance metrics string
        """
        metrics = {
            "operation": operation,
            "duration_ms": duration * 1000,
            "success": success,
            "error_message": error_message,
            "timestamp": "2026-02-02T00:00:00Z"  # Should be actual timestamp
        }
        return json.dumps(metrics, indent=2)


# Example usage and templates
EXAMPLE_TEMPLATES = {
    "message": {
        "description": "Basic message template for sending to Kafka",
        "template": MessageProcessorPrompt.create_message_template(
            "my-topic",
            "Hello, Kafka!",
            "message-key",
            {"source": "mcp", "timestamp": "2026-02-02T00:00:00Z"}
        )
    },
    "batch": {
        "description": "Batch message template for multiple messages",
        "template": MessageProcessorPrompt.create_batch_message_template([
            {"topic": "topic1", "value": "message1", "key": "key1"},
            {"topic": "topic2", "value": "message2", "key": "key2"}
        ])
    },
    "error": {
        "description": "Error handling template",
        "template": ErrorHandlerPrompt.create_error_template(
            "producer_error",
            "Failed to send message: Connection timeout",
            {"topic": "my-topic", "attempt": 3}
        )
    },
    "producer_config": {
        "description": "Producer configuration template",
        "template": ConfigurationPrompt.create_producer_config_template(
            "localhost:9092",
            acks="all",
            retries=3
        )
    },
    "consumer_config": {
        "description": "Consumer configuration template",
        "template": ConfigurationPrompt.create_consumer_config_template(
            "localhost:9092",
            group_id="my-group",
            auto_offset_reset="earliest"
        )
    }
}