import uuid
from datetime import datetime, timezone
from typing import Any, Optional
from sqlalchemy import (
    Boolean,
    Float,
    ForeignKey,
    Index,
    Integer,
    String,
    Text,
    DateTime,
)
from sqlalchemy.dialects.postgresql import UUID, JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
from infrastructure.database.base import (
    Base,
    UUIDPrimaryKeyMixin,
    TimestampMixin,
    TenantMixin,
)


class MarketplaceTemplate(Base, TimestampMixin):
    """
    Global catalog of ready-made bot blueprints and production templates.
    Contains complete architectural manifests, configuration schemas, and recommended integrations.
    """
    __tablename__ = "marketplace_templates"

    id: Mapped[str] = mapped_column(String(64), primary_key=True)  # unique slug: e.g. "bot_ecommerce_concierge"
    name: Mapped[str] = mapped_column(String(150), nullable=False)
    headline: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[str] = mapped_column(Text, nullable=False)
    category: Mapped[str] = mapped_column(String(50), index=True, nullable=False)  # business | community | ai_specialist | developer_tools | content_media
    icon: Mapped[str] = mapped_column(String(100), default="bot", 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)
    is_official: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    is_featured: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    rating: Mapped[float] = mapped_column(Float, default=5.0, nullable=False)
    install_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    supported_channels: Mapped[list[str]] = mapped_column(JSONB, default=lambda: ["telegram"], nullable=False)
    required_permissions: Mapped[list[str]] = mapped_column(JSONB, default=list, nullable=False)
    config_schema: Mapped[dict[str, Any]] = mapped_column(JSONB, default=dict, nullable=False)
    default_config: Mapped[dict[str, Any]] = mapped_column(JSONB, default=dict, nullable=False)
    system_templates: Mapped[list[str]] = mapped_column(JSONB, default=list, nullable=False)
    mcp_tools: Mapped[list[str]] = mapped_column(JSONB, default=list, nullable=False)
    modules: Mapped[list[dict[str, Any]]] = mapped_column(JSONB, default=list, nullable=False)
    manifest: Mapped[dict[str, Any]] = mapped_column(JSONB, default=dict, nullable=False)
    tags: Mapped[list[str]] = mapped_column(JSONB, default=list, nullable=False)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)

    installations: Mapped[list["InstalledBotInstance"]] = relationship("InstalledBotInstance", back_populates="template", lazy="selectin")


class MarketplaceModule(Base, TimestampMixin):
    """
    Reusable feature modules that can be added to bots (e.g., cart_manager, captcha_shield, payment_gate).
    """
    __tablename__ = "marketplace_modules"

    id: Mapped[str] = mapped_column(String(64), primary_key=True)  # unique slug: e.g. "module_cart_manager"
    name: Mapped[str] = mapped_column(String(100), nullable=False)
    description: Mapped[str] = mapped_column(String(500), nullable=False)
    category: Mapped[str] = mapped_column(String(50), nullable=False)
    version: Mapped[str] = mapped_column(String(20), default="1.0.0", nullable=False)
    icon: Mapped[str] = mapped_column(String(100), default="package", nullable=False)
    config_schema: Mapped[dict[str, Any]] = mapped_column(JSONB, 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)


class InstalledBotInstance(Base, UUIDPrimaryKeyMixin, TenantMixin, TimestampMixin):
    """
    A tenant's active installed instance of a ready-made bot from the marketplace.
    Can be configured, customized, and bound to a live Telegram Bot.
    """
    __tablename__ = "installed_bot_instances"

    template_id: Mapped[str] = mapped_column(
        String(64),
        ForeignKey("marketplace_templates.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    bot_id: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("bots.id", ondelete="SET NULL"),
        nullable=True,
        index=True,
    )
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    version_installed: Mapped[str] = mapped_column(String(20), default="1.0.0", nullable=False)
    status: Mapped[str] = mapped_column(String(50), default="configured", nullable=False)  # configured | deployed | stopped | error
    custom_config: Mapped[dict[str, Any]] = mapped_column(JSONB, default=dict, nullable=False)
    installed_modules: Mapped[list[str]] = mapped_column(JSONB, default=list, nullable=False)
    enabled_mcp_tools: Mapped[list[str]] = mapped_column(JSONB, default=list, nullable=False)
    last_deployed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
    health_status: Mapped[str] = mapped_column(String(50), default="healthy", nullable=False)
    metrics: Mapped[dict[str, Any]] = mapped_column(
        JSONB,
        default=lambda: {"total_interactions": 0, "active_users": 0, "uptime_pct": 100.0},
        nullable=False,
    )

    template: Mapped["MarketplaceTemplate"] = relationship("MarketplaceTemplate", back_populates="installations", lazy="selectin")

    __table_args__ = (
        Index("ix_installed_bot_tenant_template", "tenant_id", "template_id"),
    )
