from pydantic import BaseModel
from typing import List, Dict, Any, Optional
import os


class KafkaConfig(BaseModel):
    # Connection settings
    bootstrap_servers: List[str] = ["kafka:29092"]
    
    # Topic settings
    topic_prefix: str = "payment_events_"
    
    # Consumer settings
    consumer_group_prefix: str = "payment_gateway"
    
    # Producer settings``
    wait_for_delivery: bool = False
    
    # Advanced Kafka configurations
    producer_config: Dict[str, Any] = {
        "acks": "all",  # Wait for all replicas to acknowledge
        # "retries": 3,
        # "batch_size": 16384,
        "linger_ms": 10,
        # "buffer_memory": 33554432,
        "compression_type": "gzip",
        # "max_in_flight_requests_per_connection": 1,
        "enable_idempotence": True,
    }
    
    consumer_config: Dict[str, Any] = {
        "auto_offset_reset": "earliest",
        "enable_auto_commit": True,
        "auto_commit_interval_ms": 1000,
        "session_timeout_ms": 30000,
        "heartbeat_interval_ms": 3000,
        "max_poll_records": 500,
        "fetch_min_bytes": 1,
        "fetch_max_wait_ms": 500,
    }
    
    @classmethod
    def from_env(cls) -> "KafkaConfig":
        """Create Kafka config from environment variables"""
        bootstrap_servers = os.getenv("KAFKA_BOOTSTRAP_SERVERS", "kafka:29092").split(",")
        
        return cls(
            bootstrap_servers=bootstrap_servers,
            topic_prefix=os.getenv("KAFKA_TOPIC_PREFIX", "payment_events_"),
            consumer_group_prefix=os.getenv("KAFKA_CONSUMER_GROUP_PREFIX", "payment_gateway"),
            wait_for_delivery=os.getenv("KAFKA_WAIT_FOR_DELIVERY", "false").lower() == "true",
        )


# Default configuration
default_kafka_config = KafkaConfig()


# Environment-based configuration
def get_kafka_config() -> KafkaConfig:
    """Get Kafka configuration based on environment"""
    environment = os.getenv("ENVIRONMENT", "development")
    
    if environment == "production":
        return KafkaConfig(
            bootstrap_servers=os.getenv("KAFKA_BOOTSTRAP_SERVERS", "kafka:29092").split(","),
            topic_prefix=os.getenv("KAFKA_TOPIC_PREFIX", "payment_events_"),
            consumer_group_prefix=os.getenv("KAFKA_CONSUMER_GROUP_PREFIX", "payment_gateway"),
            wait_for_delivery=True,  # Enable in production for reliability
            producer_config={
                "acks": "all",
                "retries": 10,
                "batch_size": 32768,
                "linger_ms": 5,
                "buffer_memory": 67108864,
                "compression_type": "lz4",
                "max_in_flight_requests_per_connection": 5,
                "enable_idempotence": True,
                "request_timeout_ms": 30000,
                "retry_backoff_ms": 100,
            },
            consumer_config={
                "auto_offset_reset": "earliest",
                "enable_auto_commit": True,
                "auto_commit_interval_ms": 5000,
                "session_timeout_ms": 45000,
                "heartbeat_interval_ms": 3000,
                "max_poll_records": 100,
                "fetch_min_bytes": 1024,
                "fetch_max_wait_ms": 500,
                "isolation_level": "read_committed",
            }
        )
    else:
        # Development configuration
        return KafkaConfig.from_env()