"""Usage domain — SQLAlchemy models."""
from __future__ import annotations

from datetime import date, datetime
from decimal import Decimal
from typing import Optional
from uuid import UUID, uuid4

from sqlalchemy import BigInteger, Date, ForeignKey, Numeric, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.sql import func
from sqlalchemy.types import DateTime

from src.core.database import Base


class WorkspaceUsageSnapshot(Base):
    """Daily workspace-aggregate usage snapshot — source of truth for billing.

    One row per (workspace_id, snapshot_date). Written by the daily arq task that
    pulls from Cloud's cloud_project_usage_snapshots and sums across projects.
    """

    __tablename__ = "workspace_usage_snapshots"

    id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=uuid4)
    workspace_id: Mapped[UUID] = mapped_column(
        PGUUID(as_uuid=True),
        ForeignKey("workspaces.id", ondelete="CASCADE"),
        nullable=False,
    )
    snapshot_date: Mapped[date] = mapped_column(Date, nullable=False)
    cpu_minutes: Mapped[Decimal] = mapped_column(Numeric(12, 4), nullable=False, default=0)
    db_reads: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
    db_writes: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
    storage_gb: Mapped[Decimal] = mapped_column(Numeric(12, 6), nullable=False, default=0)
    cdn_gb: Mapped[Decimal] = mapped_column(Numeric(12, 6), nullable=False, default=0)
    hosted_app_requests: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
    hosted_app_egress_bytes: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
    auth_users_active: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
    ai_embed_tokens: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
    ai_completion_tokens: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
    ai_searches: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
    job_executions: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
    realtime_minutes: Mapped[Decimal] = mapped_column(Numeric(12, 4), nullable=False, default=0)
    ext_queries: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
    credits_consumed: Mapped[Decimal] = mapped_column(Numeric(12, 6), nullable=False, default=0)
    # Credit exhaustion notification dedup — reset each billing period
    notified_50pct_at: Mapped[Optional[datetime]] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
    notified_90pct_at: Mapped[Optional[datetime]] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )

    __table_args__ = (
        UniqueConstraint(
            "workspace_id", "snapshot_date",
            name="uq_workspace_usage_snapshot_date",
        ),
    )


class ProjectHostedAppUsageSnapshot(Base):
    """Daily hosted-app edge traffic, retained separately from Cloud service usage."""

    __tablename__ = "project_hosted_app_usage_snapshots"

    id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=uuid4)
    workspace_id: Mapped[UUID] = mapped_column(
        PGUUID(as_uuid=True),
        ForeignKey("workspaces.id", ondelete="CASCADE"),
        nullable=False,
    )
    project_id: Mapped[UUID] = mapped_column(
        PGUUID(as_uuid=True),
        ForeignKey("projects.id", ondelete="CASCADE"),
        nullable=False,
    )
    snapshot_date: Mapped[date] = mapped_column(Date, nullable=False)
    requests: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
    egress_bytes: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )

    __table_args__ = (
        UniqueConstraint(
            "project_id", "snapshot_date",
            name="uq_project_hosted_app_usage_snapshot_date",
        ),
    )
