"""
Client Model - Companies/Organizations using the service
"""
from datetime import datetime
import secrets
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, JSON, ForeignKey, Enum as SQLEnum
from sqlalchemy.orm import relationship
import enum

from app.models.base import Base, TimestampMixin, SoftDeleteMixin


class ClientStatus(enum.Enum):
    ACTIVE = "active"
    INACTIVE = "inactive"
    SUSPENDED = "suspended"
    TRIAL = "trial"


class Client(Base, TimestampMixin, SoftDeleteMixin):
    """
    Client/Organization Model
    Represents a company or individual using the AI services
    """
    __tablename__ = "clients"

    id = Column(Integer, primary_key=True, index=True)

    # Company Information
    company_name = Column(String(255), nullable=False, index=True)
    company_email = Column(String(255), unique=True, nullable=False, index=True)
    company_phone = Column(String(20), nullable=True)
    company_website = Column(String(255), nullable=True)
    company_address = Column(Text, nullable=True)
    company_logo_url = Column(String(500), nullable=True)

    # Industry & Size
    industry = Column(String(100), nullable=True)
    company_size = Column(String(50), nullable=True)  # 1-10, 11-50, 51-200, 201-500, 500+

    # Contact Person
    contact_name = Column(String(255), nullable=False)
    contact_email = Column(String(255), nullable=False)
    contact_phone = Column(String(20), nullable=True)
    contact_designation = Column(String(100), nullable=True)

    # Account Settings
    status = Column(SQLEnum(ClientStatus), default=ClientStatus.TRIAL, nullable=False)
    plan_id = Column(Integer, ForeignKey("plans.id"), nullable=True)

    # Chatbot Configuration
    chatbot_name = Column(String(100), default="AI Assistant")
    chatbot_welcome_message = Column(Text, default="Hello! How can I help you today?")
    chatbot_system_prompt = Column(Text, nullable=True)
    chatbot_primary_color = Column(String(7), default="#2563eb")
    chatbot_model = Column(String(50), default="gpt-4o-mini")
    chatbot_max_tokens = Column(Integer, default=1000)

    # Custom Knowledge Base
    custom_instructions = Column(Text, nullable=True)
    faq_data = Column(JSON, nullable=True)  # Store FAQ as JSON

    # Limits
    monthly_message_limit = Column(Integer, default=1000)
    daily_message_limit = Column(Integer, default=100)

    # Trial Info
    trial_ends_at = Column(DateTime, nullable=True)

    # Metadata
    timezone = Column(String(50), default="Asia/Kolkata")
    language = Column(String(10), default="en")

    # Relationships
    api_keys = relationship("ClientAPIKey", back_populates="client", cascade="all, delete-orphan")
    conversations = relationship("Conversation", back_populates="client", cascade="all, delete-orphan")
    subscriptions = relationship("Subscription", back_populates="client", cascade="all, delete-orphan")
    invoices = relationship("Invoice", back_populates="client", cascade="all, delete-orphan")
    usage_logs = relationship("UsageLog", back_populates="client", cascade="all, delete-orphan")
    users = relationship("User", back_populates="client", cascade="all, delete-orphan")
    webhooks = relationship("ClientWebhook", back_populates="client", cascade="all, delete-orphan")

    def __repr__(self):
        return f"<Client(id={self.id}, company_name='{self.company_name}')>"


class ClientAPIKey(Base, TimestampMixin):
    """
    API Keys for client authentication
    """
    __tablename__ = "client_api_keys"

    id = Column(Integer, primary_key=True, index=True)
    client_id = Column(Integer, ForeignKey("clients.id"), nullable=False)

    # Key Details
    key_name = Column(String(100), nullable=False)  # e.g., "Production", "Development"
    api_key = Column(String(64), unique=True, nullable=False, index=True)
    secret_key = Column(String(64), nullable=False)

    # Permissions
    is_active = Column(Boolean, default=True)
    permissions = Column(JSON, default=["chat"])  # chat, analytics, vision

    # Rate Limiting
    rate_limit_per_minute = Column(Integer, default=60)
    rate_limit_per_day = Column(Integer, default=10000)

    # Usage Tracking
    last_used_at = Column(DateTime, nullable=True)
    total_requests = Column(Integer, default=0)

    # Expiry
    expires_at = Column(DateTime, nullable=True)

    # Allowed Origins (CORS)
    allowed_origins = Column(JSON, default=["*"])

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

    @staticmethod
    def generate_api_key():
        """Generate a secure API key"""
        return f"ak_{secrets.token_hex(24)}"

    @staticmethod
    def generate_secret_key():
        """Generate a secure secret key"""
        return f"sk_{secrets.token_hex(24)}"

    def __repr__(self):
        return f"<ClientAPIKey(id={self.id}, key_name='{self.key_name}')>"
