import uuid
from datetime import datetime, timezone
from typing import Optional, TYPE_CHECKING
from sqlalchemy import Integer, Text, DateTime, ForeignKey
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.account import Account
    from app.models.user import User


class AccountLimitOverride(Base):
    __tablename__ = "account_limit_overrides"

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    account_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("accounts.id", ondelete="CASCADE"),
        unique=True,
        nullable=False
    )
    override_max_trees: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
    override_max_sessions_per_month: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
    override_max_users: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
    override_max_ai_builds_per_month: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
    override_max_ai_builds_per_24h: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
    note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    created_by_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("users.id"),
        nullable=False
    )
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        default=lambda: datetime.now(timezone.utc),
        onupdate=lambda: datetime.now(timezone.utc)
    )

    # Relationships
    account: Mapped["Account"] = relationship("Account", back_populates="limit_override")
    created_by: Mapped["User"] = relationship("User")
