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

from datetime import datetime
from typing import Optional
from uuid import UUID, uuid4

from sqlalchemy import Boolean, ForeignKey, Integer, String, Text, UniqueConstraint
from sqlalchemy.dialects.postgresql import JSONB, 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 ProjectLogConfig(Base):
    """Per-project log settings. One row per project (upsert pattern).

    debug_enabled and debug_expires_at are pushed to Cloud KV so workers
    can decide whether to write debug entries.
    retention_days is derived from plan and pushed to Cloud for pc-scheduler cleanup.
    """

    __tablename__ = "project_log_config"

    id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=uuid4)
    project_id: Mapped[UUID] = mapped_column(
        PGUUID(as_uuid=True),
        ForeignKey("projects.id", ondelete="CASCADE"),
        nullable=False,
        unique=True,
    )
    debug_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
    debug_expires_at: Mapped[Optional[datetime]] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
    min_drain_level: Mapped[str] = mapped_column(String(10), nullable=False, default="info")
    retention_days: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )


class ProjectLogDrain(Base):
    """External log drain destination for a project.

    auth_secret_enc is Fernet-encrypted; Core holds the key, Cloud receives an
    opaque secret_ref when draining (same pattern as integrations).
    """

    __tablename__ = "project_log_drains"

    id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=uuid4)
    project_id: Mapped[UUID] = mapped_column(
        PGUUID(as_uuid=True),
        ForeignKey("projects.id", ondelete="CASCADE"),
        nullable=False,
    )
    name: Mapped[str] = mapped_column(String(64), nullable=False)
    # logtail | datadog | custom_webhook
    destination_type: Mapped[str] = mapped_column(String(32), nullable=False)
    endpoint_url: Mapped[str] = mapped_column(Text, nullable=False)
    auth_secret_enc: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    min_level: Mapped[str] = mapped_column(String(10), nullable=False, default="info")
    sources_json: Mapped[Optional[list]] = mapped_column(JSONB, nullable=True)
    enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )

    __table_args__ = (
        UniqueConstraint("project_id", "name", name="uq_log_drain_project_name"),
    )
