"""
Kafka resources module for FastMCP.

This module defines MCP resources for Kafka system status and monitoring.
"""

import json
import asyncio
import logging
from typing import Dict, Any, Optional, Callable

from mcp.server.fastmcp import FastMCP

from kafka_integration import KafkaModule


def register_kafka_resources(kafka_module: KafkaModule, mcp: Any):
    """
    Register all Kafka resources with FastMCP.

    Args:
        kafka_module: KafkaModule instance
        mcp: FastMCP instance
    """

    # System status resource
    @mcp.resource("kafka://status")
    def kafka_status_resource() -> str:
        """
        Get overall Kafka module status and configuration.

        Returns:
            JSON string with status information
        """
        status = kafka_module.get_status()
        return json.dumps(status, indent=2)

    # Topic info resource
    @mcp.resource("kafka://topics/{topic}")
    async def kafka_topic_resource(topic: str) -> str:
        """
        Get detailed information about a specific Kafka topic.

        Args:
            topic: Name of the topic

        Returns:
            JSON string with topic information
        """
        try:
            result = await kafka_module.describe_topic(topic)
            return json.dumps(result, indent=2)
        except Exception as e:
            return json.dumps({
                "success": False,
                "error": str(e),
                "topic": topic
            }, indent=2)

    # Consumer group info resource
    @mcp.resource("kafka://consumers/{group}")
    async def kafka_consumer_group_resource(group: str) -> str:
        """
        Get detailed information about a specific consumer group.

        Args:
            group: ID of the consumer group

        Returns:
            JSON string with consumer group information
        """
        try:
            result = await kafka_module.describe_consumer_group(group)
            return json.dumps(result, indent=2)
        except Exception as e:
            return json.dumps({
                "success": False,
                "error": str(e),
                "group_id": group
            }, indent=2)

    # Topics list resource
    @mcp.resource("kafka://topics")
    async def kafka_topics_list_resource() -> str:
        """
        Get list of all topics in the Kafka cluster.

        Returns:
            JSON string with topics list
        """
        try:
            result = await kafka_module.list_topics()
            return json.dumps(result, indent=2)
        except Exception as e:
            return json.dumps({
                "success": False,
                "error": str(e)
            }, indent=2)

    # Consumer groups list resource
    @mcp.resource("kafka://consumers")
    async def kafka_consumers_list_resource() -> str:
        """
        Get list of all consumer groups in the Kafka cluster.

        Returns:
            JSON string with consumer groups list
        """
        try:
            result = await kafka_module.list_consumer_groups()
            return json.dumps(result, indent=2)
        except Exception as e:
            return json.dumps({
                "success": False,
                "error": str(e)
            }, indent=2)

    logging.info("Kafka resources registered successfully")


class KafkaResourceMonitor:
    """Monitor for updating Kafka resources periodically."""

    def __init__(self, kafka_module: KafkaModule, update_interval: float = 10.0):
        """
        Initialize resource monitor.

        Args:
            kafka_module: KafkaModule instance
            update_interval: Update interval in seconds
        """
        self.kafka_module = kafka_module
        self.update_interval = update_interval
        self.tasks: Dict[str, asyncio.Task] = {}
        self.is_running = False

    async def start_monitoring(self):
        """Start periodic monitoring of Kafka resources."""
        self.is_running = True

        # Create tasks for each resource
        topics_task = asyncio.create_task(self._monitor_topics())
        consumers_task = asyncio.create_task(self._monitor_consumers())
        status_task = asyncio.create_task(self._monitor_status())

        self.tasks = {
            "topics": topics_task,
            "consumers": consumers_task,
            "status": status_task
        }

        logging.info("Kafka resource monitoring started")

    async def stop_monitoring(self):
        """Stop periodic monitoring."""
        self.is_running = False

        # Cancel all tasks
        for task in self.tasks.values():
            if not task.done():
                task.cancel()

        self.tasks.clear()
        logging.info("Kafka resource monitoring stopped")

    async def _monitor_topics(self):
        """Monitor topics periodically."""
        while self.is_running:
            try:
                await self._update_topics_resource()
                await asyncio.sleep(self.update_interval)
            except Exception as e:
                logging.error(f"Error monitoring topics: {e}")
                await asyncio.sleep(self.update_interval)

    async def _monitor_consumers(self):
        """Monitor consumer groups periodically."""
        while self.is_running:
            try:
                await self._update_consumers_resource()
                await asyncio.sleep(self.update_interval)
            except Exception as e:
                logging.error(f"Error monitoring consumers: {e}")
                await asyncio.sleep(self.update_interval)

    async def _monitor_status(self):
        """Monitor status periodically."""
        while self.is_running:
            try:
                await self._update_status_resource()
                await asyncio.sleep(self.update_interval)
            except Exception as e:
                logging.error(f"Error monitoring status: {e}")
                await asyncio.sleep(self.update_interval)

    async def _update_topics_resource(self):
        """Update topics resource."""
        try:
            result = await self.kafka_module.list_topics()
            # In a real implementation, this would update the FastMCP resource
            # For now, we just log the update
            logging.debug("Topics resource updated")
        except Exception as e:
            logging.error(f"Failed to update topics resource: {e}")

    async def _update_consumers_resource(self):
        """Update consumers resource."""
        try:
            result = await self.kafka_module.list_consumer_groups()
            logging.debug("Consumers resource updated")
        except Exception as e:
            logging.error(f"Failed to update consumers resource: {e}")

    async def _update_status_resource(self):
        """Update status resource."""
        try:
            status = self.kafka_module.get_status()
            logging.debug("Status resource updated")
        except Exception as e:
            logging.error(f"Failed to update status resource: {e}")