from datetime import datetime
from typing import Optional
from uuid import UUID
from pydantic import BaseModel, Field
import re


def slugify(name: str) -> str:
    """Convert a tag name to a URL-safe slug."""
    # 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


class TagBase(BaseModel):
    name: str = Field(..., min_length=1, max_length=50)


class TagCreate(TagBase):
    account_id: Optional[UUID] = Field(None, description="Account ID for account-specific tag. NULL for global.")


class TagResponse(TagBase):
    id: UUID
    slug: str
    account_id: Optional[UUID] = None
    usage_count: int
    created_at: datetime

    class Config:
        from_attributes = True


class TagListResponse(BaseModel):
    id: UUID
    name: str
    slug: str
    account_id: Optional[UUID] = None
    usage_count: int

    class Config:
        from_attributes = True


class TagAssignment(BaseModel):
    """Request body for adding/removing tags from a tree."""
    tags: list[str] = Field(..., min_length=1, max_length=10, description="List of tag names to assign")


class TagSearchParams(BaseModel):
    """Query parameters for tag search/autocomplete."""
    q: str = Field(..., min_length=1, description="Search query")
    limit: int = Field(10, ge=1, le=50)
    include_account: bool = Field(True, description="Include account-specific tags")
