import uuid
from typing import Any, Optional
from sqlalchemy import (
    Boolean,
    ForeignKey,
    Index,
    JSON,
    String,
    UniqueConstraint,
)
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from infrastructure.database.base import (
    Base,
    UUIDPrimaryKeyMixin,
    TimestampMixin,
    TenantMixin,
)


class Plugin(Base, TimestampMixin):
    """Global catalog of registered plugins available for tenant activation."""
    __tablename__ = "plugins"

    id: Mapped[str] = mapped_column(String(50), primary_key=True)  # unique slug
    name: Mapped[str] = mapped_column(String(100), nullable=False)
    description: Mapped[str] = mapped_column(String(500), nullable=False)
    version: Mapped[str] = mapped_column(String(20), default="1.0.0", nullable=False)
    author: Mapped[str] = mapped_column(String(100), default="Platform Core", nullable=False)
    category: Mapped[str] = mapped_column(String(50), default="utility", nullable=False)  # security | utility | monetization | integration
    required_permissions: Mapped[list[str]] = mapped_column(JSON, default=list, nullable=False)
    default_config: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, nullable=False)
    is_official: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)

    installations: Mapped[list["TenantPlugin"]] = relationship("TenantPlugin", back_populates="plugin")


class TenantPlugin(Base, UUIDPrimaryKeyMixin, TenantMixin, TimestampMixin):
    """Tenant/Bot-specific activation and isolated configuration of a plugin."""
    __tablename__ = "tenant_plugins"

    plugin_id: Mapped[str] = mapped_column(
        String(50),
        ForeignKey("plugins.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    bot_id: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("bots.id", ondelete="CASCADE"),
        nullable=True,
        index=True,
    )
    is_enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    config: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, nullable=False)
    installed_version: Mapped[str] = mapped_column(String(20), default="1.0.0", nullable=False)
    granted_permissions: Mapped[list[str]] = mapped_column(JSON, default=list, nullable=False)

    plugin: Mapped["Plugin"] = relationship("Plugin", back_populates="installations")

    __table_args__ = (
        UniqueConstraint("tenant_id", "bot_id", "plugin_id", name="uq_tenant_bot_plugin"),
    )
