"""
Service Configuration Model
Stores configuration for each microservice per client
"""
from sqlalchemy import Column, String, Integer, Boolean, DateTime, JSON, ForeignKey, Text
from sqlalchemy.orm import relationship
from datetime import datetime
import enum

from app.models.base import BaseModel


class ServiceType(str, enum.Enum):
    CHATBOT = "chatbot"
    VOICE_AGENT = "voice_agent"
    DOCUMENT_INTELLIGENCE = "document_intelligence"
    ANALYTICS = "analytics"
    VISION = "vision"


class ServiceConfig(BaseModel):
    """
    Service configuration for each client
    Each client can have different settings for each service
    """
    __tablename__ = "service_configs"

    client_id = Column(Integer, ForeignKey("clients.id", ondelete="CASCADE"), nullable=False, index=True)
    service_type = Column(String(50), nullable=False)

    # Service Status
    is_enabled = Column(Boolean, default=True)
    is_active = Column(Boolean, default=True)

    # AI Provider Configuration
    ai_provider = Column(String(50), default="openai")  # openai, anthropic, google, azure
    ai_model = Column(String(100), default="gpt-4")
    ai_api_key = Column(Text, nullable=True)  # Encrypted in production

    # Service-specific settings (JSON)
    settings = Column(JSON, default=dict)

    # Usage limits
    daily_limit = Column(Integer, nullable=True)
    monthly_limit = Column(Integer, nullable=True)
    rate_limit_per_minute = Column(Integer, default=60)

    # Webhook configuration
    webhook_url = Column(String(500), nullable=True)
    webhook_secret = Column(String(255), nullable=True)
    webhook_events = Column(JSON, default=list)  # List of events to send

    # Custom branding
    branding = Column(JSON, default=dict)  # logo, colors, welcome message, etc.

    # Relationships
    client = relationship("Client", back_populates="service_configs")

    def __repr__(self):
        return f"<ServiceConfig {self.client_id}:{self.service_type}>"


class ServiceCredential(BaseModel):
    """
    Stores API credentials for third-party services
    Used by microservices to access external APIs
    """
    __tablename__ = "service_credentials"

    client_id = Column(Integer, ForeignKey("clients.id", ondelete="CASCADE"), nullable=False, index=True)
    service_type = Column(String(50), nullable=False)

    # Credential Details
    provider = Column(String(50), nullable=False)  # openai, twilio, aws, google, etc.
    credential_type = Column(String(50), nullable=False)  # api_key, oauth, service_account

    # Encrypted credentials
    credentials = Column(JSON, nullable=False)  # Encrypted JSON with keys

    # Status
    is_active = Column(Boolean, default=True)
    is_verified = Column(Boolean, default=False)
    last_verified_at = Column(DateTime, nullable=True)

    # Metadata
    name = Column(String(100), nullable=True)  # Friendly name
    description = Column(Text, nullable=True)
    expires_at = Column(DateTime, nullable=True)

    # Relationships
    client = relationship("Client", back_populates="service_credentials")

    def __repr__(self):
        return f"<ServiceCredential {self.provider}:{self.service_type}>"


# Default configurations for each service type
DEFAULT_SERVICE_CONFIGS = {
    ServiceType.CHATBOT: {
        "ai_provider": "openai",
        "ai_model": "gpt-4",
        "settings": {
            "max_tokens": 2000,
            "temperature": 0.7,
            "system_prompt": "You are a helpful customer support assistant.",
            "welcome_message": "Hello! How can I help you today?",
            "fallback_message": "I'm sorry, I didn't understand that. Can you please rephrase?",
            "enable_memory": True,
            "memory_window": 10,
            "enable_typing_indicator": True,
            "response_delay_ms": 500
        },
        "branding": {
            "bot_name": "AI Assistant",
            "bot_avatar": None,
            "primary_color": "#007bff",
            "chat_position": "bottom-right"
        }
    },
    ServiceType.VOICE_AGENT: {
        "ai_provider": "openai",
        "ai_model": "gpt-4",
        "settings": {
            "voice_provider": "elevenlabs",
            "voice_id": "default",
            "language": "en-US",
            "speech_rate": 1.0,
            "enable_transcription": True,
            "max_call_duration_seconds": 600,
            "silence_timeout_seconds": 30
        }
    },
    ServiceType.DOCUMENT_INTELLIGENCE: {
        "ai_provider": "openai",
        "ai_model": "gpt-4-vision-preview",
        "settings": {
            "supported_formats": ["pdf", "docx", "xlsx", "png", "jpg"],
            "max_file_size_mb": 50,
            "enable_ocr": True,
            "enable_table_extraction": True,
            "enable_entity_extraction": True,
            "output_format": "json"
        }
    },
    ServiceType.ANALYTICS: {
        "settings": {
            "retention_days": 90,
            "enable_real_time": True,
            "enable_exports": True,
            "export_formats": ["csv", "json", "xlsx"],
            "dashboard_refresh_interval_seconds": 30
        }
    },
    ServiceType.VISION: {
        "ai_provider": "openai",
        "ai_model": "gpt-4-vision-preview",
        "settings": {
            "supported_formats": ["png", "jpg", "jpeg", "gif", "webp"],
            "max_image_size_mb": 20,
            "enable_object_detection": True,
            "enable_text_extraction": True,
            "enable_face_detection": False,
            "confidence_threshold": 0.8
        }
    }
}
