"""
Demo MCP Server without Kafka.

This is a lightweight demo version that simulates Kafka functionality
for testing without needing a running Kafka instance.
"""

import logging
from mcp.server.fastmcp import FastMCP

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Create an MCP server
mcp = FastMCP("Demo MCP Server")

# Demo data storage (simulating Kafka)
demo_topics = {}
demo_messages = {}
demo_consumer_groups = {}

# Demo tools
@mcp.tool()
def create_topic(topic_name: str, partitions: int = 3, replication_factor: int = 1) -> str:
    """Create a new topic (demo - no actual Kafka needed)"""
    demo_topics[topic_name] = {
        "partitions": partitions,
        "replication_factor": replication_factor,
        "messages": []
    }
    demo_messages[topic_name] = []
    return f"✓ Created topic '{topic_name}' with {partitions} partitions"

@mcp.tool()
def send_message(topic: str, value: str, key: str = None) -> str:
    """Send a message to a topic (demo)"""
    if topic not in demo_topics:
        return f"✗ Error: Topic '{topic}' does not exist. Create it first."

    message = {
        "key": key,
        "value": value,
        "timestamp": "2024-01-01T00:00:00Z"
    }
    demo_messages[topic].append(message)
    return f"✓ Sent message to topic '{topic}': {value}"

@mcp.tool()
def list_topics() -> str:
    """List all topics (demo)"""
    if not demo_topics:
        return "No topics created yet. Use 'create_topic' to create one."
    topics_list = "\n".join([f"- {name} ({info['partitions']} partitions)" for name, info in demo_topics.items()])
    return f"Available topics:\n{topics_list}"

@mcp.tool()
def consume_messages(topic: str) -> str:
    """Consume messages from a topic (demo)"""
    if topic not in demo_messages or not demo_messages[topic]:
        return f"No messages in topic '{topic}'"

    messages = demo_messages[topic]
    result = f"Messages in '{topic}':\n"
    for i, msg in enumerate(messages[-5:], 1):  # Show last 5
        key_part = f"[{msg['key']}] " if msg['key'] else ""
        result += f"{i}. {key_part}{msg['value']}\n"
    return result

# Demo resource
@mcp.resource("demo://status")
def get_status() -> str:
    """Get demo server status"""
    return f"""Demo MCP Server Status:
✓ Server is running
✓ Topics created: {len(demo_topics)}
✓ Total messages: {sum(len(msgs) for msgs in demo_messages.values())}
✓ Kafka: Simulated (demo mode)

Available tools:
- create_topic: Create a new topic
- send_message: Send a message to a topic
- list_topics: List all topics
- consume_messages: Get messages from a topic
"""

# Demo prompt
@mcp.prompt()
def help_prompt() -> str:
    """Get help using the demo server"""
    return """Welcome to the Demo MCP Server!

This is a demonstration version that simulates Kafka functionality
without needing a running Kafka instance.

Getting Started:
1. Create a topic: create_topic("my-topic", partitions=3)
2. Send a message: send_message("my-topic", "Hello, World!", "greeting")
3. List topics: list_topics()
4. Consume messages: consume_messages("my-topic")

All data is stored in memory and will be reset when the server stops.
"""

# Add a simple calculator tool (from original demo)
@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b


def main():
    """Entry point for the kk-mcp-demo command."""
    logger.info("Starting Demo MCP Server (no Kafka required)...")
    mcp.run(transport="stdio")


# Run with streamable HTTP transport
if __name__ == "__main__":
    main()