import uuid
from datetime import datetime, timezone
from typing import Optional, TYPE_CHECKING
from sqlalchemy import String, DateTime, ForeignKey, Integer, UniqueConstraint, Table, Column
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.dialects.postgresql import UUID
from app.core.database import Base

if TYPE_CHECKING:
    from app.models.tree import Tree
    from app.models.team import Team
    from app.models.account import Account
    from app.models.user import User


# Junction table for tree-tag many-to-many relationship
tree_tag_assignments = Table(
    'tree_tag_assignments',
    Base.metadata,
    Column('tree_id', UUID(as_uuid=True), ForeignKey('trees.id', ondelete='CASCADE'), primary_key=True),
    Column('tag_id', UUID(as_uuid=True), ForeignKey('tree_tags.id', ondelete='CASCADE'), primary_key=True),
    Column('assigned_by', UUID(as_uuid=True), ForeignKey('users.id', ondelete='SET NULL'), nullable=True),
    Column('assigned_at', DateTime(timezone=True), nullable=False, default=lambda: datetime.now(timezone.utc))
)


class TreeTag(Base):
    """Tags for categorizing and filtering trees.

    Tags can be:
    - Global (team_id=NULL): Available to all users
    - Team-specific (team_id set): Only visible to team members

    Tags are managed by tree authors and admins (global or team).
    """
    __tablename__ = "tree_tags"
    __table_args__ = (
        UniqueConstraint('slug', 'team_id', name='uq_tree_tags_slug_team'),
    )

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        primary_key=True,
        default=uuid.uuid4
    )
    name: Mapped[str] = mapped_column(String(50), nullable=False)
    slug: Mapped[str] = mapped_column(String(50), nullable=False, index=True)
    team_id: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("teams.id", ondelete="CASCADE"),
        nullable=True,
        index=True
    )
    account_id: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("accounts.id", ondelete="CASCADE"),
        nullable=True,
        index=True
    )
    usage_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, index=True)
    created_by: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("users.id", ondelete="SET NULL"),
        nullable=True
    )
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        default=lambda: datetime.now(timezone.utc)
    )

    # Relationships
    team: Mapped[Optional["Team"]] = relationship("Team", back_populates="tags")
    account: Mapped[Optional["Account"]] = relationship("Account", foreign_keys=[account_id], back_populates="tags")
    creator: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by])
    trees: Mapped[list["Tree"]] = relationship(
        "Tree",
        secondary=tree_tag_assignments,
        back_populates="tags"
    )

    @property
    def is_global(self) -> bool:
        """Returns True if this is a global tag (not team or account-specific)."""
        return self.team_id is None and self.account_id is None

    @classmethod
    def slugify(cls, name: str) -> str:
        """Convert a tag name to a URL-safe slug."""
        import re
        # Remove non-alphanumeric chars except spaces, convert to lowercase
        slug = re.sub(r'[^a-zA-Z0-9 ]', '', name.lower())
        # Replace spaces with hyphens
        slug = re.sub(r' +', '-', slug.strip())
        return slug
