import json
import uuid
from datetime import datetime

from sqlalchemy import Boolean, DateTime, Integer, String, Text, Uuid, func
from sqlalchemy.orm import Mapped, mapped_column

from app.database import Base


class QualificationProtocol(Base):
    """Active configuration for the decision qualification engine.

    Thresholds stored here override the engine defaults and can be updated
    through the admin interface (meta-governance).
    Only one record should be active at a time (is_active=True).
    """
    __tablename__ = "qualification_protocols"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    name: Mapped[str] = mapped_column(String(128), nullable=False)
    description: Mapped[str | None] = mapped_column(Text)

    small_group_max: Mapped[int] = mapped_column(Integer, default=5)
    collective_wot_min: Mapped[int] = mapped_column(Integer, default=50)

    # JSON array of modality slugs, e.g. '["vote_wot","vote_smith","election"]'
    default_modalities_json: Mapped[str] = mapped_column(
        Text,
        default='["vote_wot","vote_smith","consultation_avis","election"]',
    )

    is_active: Mapped[bool] = mapped_column(Boolean, default=True)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())

    @property
    def default_modalities(self) -> list[str]:
        return json.loads(self.default_modalities_json)
