import uuid
from datetime import datetime

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

from app.database import Base


class FormulaConfig(Base):
    __tablename__ = "formula_configs"

    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)

    # WoT threshold params
    duration_days: Mapped[int] = mapped_column(Integer, default=30)
    majority_pct: Mapped[int] = mapped_column(Integer, default=50)
    base_exponent: Mapped[float] = mapped_column(Float, default=0.1)
    gradient_exponent: Mapped[float] = mapped_column(Float, default=0.2)
    constant_base: Mapped[float] = mapped_column(Float, default=0.0)

    # Smith criterion
    smith_exponent: Mapped[float | None] = mapped_column(Float)

    # TechComm criterion
    techcomm_exponent: Mapped[float | None] = mapped_column(Float)

    # Nuanced vote
    nuanced_min_participants: Mapped[int | None] = mapped_column(Integer)
    nuanced_threshold_pct: Mapped[int | None] = mapped_column(Integer)

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

    protocols: Mapped[list["VotingProtocol"]] = relationship(back_populates="formula_config")


class VotingProtocol(Base):
    __tablename__ = "voting_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)
    vote_type: Mapped[str] = mapped_column(String(32), nullable=False)  # binary, nuanced
    formula_config_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("formula_configs.id"), nullable=False)
    organization_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("organizations.id"), nullable=True, index=True)
    mode_params: Mapped[str | None] = mapped_column(String(64))  # e.g. "D30M50B.1G.2T.1"
    is_meta_governed: Mapped[bool] = mapped_column(Boolean, default=False)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())

    formula_config: Mapped["FormulaConfig"] = relationship(back_populates="protocols")
