import uuid
from datetime import datetime
from sqlalchemy import String, DateTime, Boolean
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.dialects.postgresql import UUID, JSONB
from app.database import Base

_DEFAULT_TENANT_CONFIG = {
    "max_concurrent_renders": 3,
    "render_engines_allowed": ["cycles", "eevee"],
    "max_order_size": 500,
    "fallback_material": "SCHAEFFLER_059999_FailedMaterial",
    "notifications_enabled": True,
    "invoice_prefix": "INV",
    # Azure AI validation (per-tenant)
    "ai_enabled": False,
    "ai_api_key": None,          # stored but never returned to frontend
    "ai_endpoint": None,         # e.g. https://myinstance.openai.azure.com
    "ai_deployment": "gpt-4o",
    "ai_api_version": "2024-02-01",
    "ai_max_tokens": 500,
    "ai_temperature": 0.1,
    "ai_validation_prompt": None,  # None = use DEFAULT_VALIDATION_PROMPT from azure_ai.py
}


class Tenant(Base):
    __tablename__ = "tenants"

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    name: Mapped[str] = mapped_column(String(200), nullable=False)
    slug: Mapped[str] = mapped_column(String(100), nullable=False, unique=True)
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
    tenant_config: Mapped[dict | None] = mapped_column(
        JSONB, nullable=True, default=_DEFAULT_TENANT_CONFIG
    )

    def get_config(self, key: str, default=None):
        """Safe accessor for tenant_config fields."""
        cfg = self.tenant_config or {}
        return cfg.get(key, default)

    # Relationships (lazy=noload — loaded explicitly when needed)
    users: Mapped[list] = relationship("User", back_populates="tenant", lazy="noload")
    orders: Mapped[list] = relationship("Order", back_populates="tenant", lazy="noload")
    products: Mapped[list] = relationship("Product", back_populates="tenant", lazy="noload")
