from sqlalchemy import Column, String, DateTime
from datetime import datetime
from sqlmodel import Field
import uuid

from fmatch.saas.db import Base


def _id() -> str:
    return str(uuid.uuid4())


class C2APolicy(Base, table=True):
    __tablename__ = "c2a_policies"
    __table_args__ = {"extend_existing": True}

    id: str = Field(primary_key=True, default_factory=_id)
    account_id: str = Field(index=True)

    # Writeback & governance
    link_writeback_mode: str = Field(default="account")  # 'account' | 'acr'
    link_overwrite_mode: str = Field(default="if_empty")  # 'if_empty'|'always'|'never'

    # Scoring & ensembles
    use_multi_algo: bool = Field(default=True)
    threshold: float = Field(default=0.70)
    min_score_gap: float = Field(default=0.05)
    # Store user-configured weights and similar knobs as compact JSON string
    weights_json: str = Field(sa_column=Column(String), default="{}")
    auto_link_tier: str = Field(default="CERTAIN")  # reserved for future

    # Upgrade behavior
    allow_upgrade: bool = Field(default=True)

    # Registry tracking (stamped by engines)
    registry_version: str = Field(default="")

    updated_at: datetime = Field(
        default_factory=datetime.utcnow,
        sa_column=Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow),
    )
