"""Autopass rules (plan §4.4) — automation as a teammate, M6.

A player can define, per match, "when a ball is passed to me from my
sub-team (or: from anyone / from player X), auto-pass it to player Y".
ONE rule per (match, owner) — the settings sheet is two dropdowns and a
toggle, deliberately (§4.4's smallest useful form); the unique constraint
makes the API's upsert semantics a schema fact, not a convention.

Execution is ONE hop max and loop-proof BY CONSTRUCTION: the auto touch
a rule produces (kind "auto", via_rule_id set) never re-enters rule
matching (services/autopass.py evaluates only the primary human touch).
The trigger vocabulary lives in services/autopass.py (plain text column,
same one-authority convention as every other enum-like column here).
"""
import datetime

from sqlalchemy import Boolean, ForeignKey, String, UniqueConstraint, text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column

from .base import Base, created_at, uuid_pk


class AutopassRule(Base):
    __tablename__ = "autopass_rules"
    __table_args__ = (
        UniqueConstraint("match_id", "owner_player_id", name="uq_autopass_owner_per_match"),
    )

    id: Mapped[str] = uuid_pk()
    match_id: Mapped[str] = mapped_column(
        UUID(as_uuid=True), ForeignKey("matches.id", ondelete="CASCADE"), nullable=False
    )
    # The player whose incoming balls the rule watches (rules are owner-
    # scoped: you manage only YOUR rule — routers/autopass.py enforces it).
    owner_player_id: Mapped[str] = mapped_column(
        UUID(as_uuid=True), ForeignKey("players.id", ondelete="CASCADE"), nullable=False
    )
    # from_subteam | from_any | from_player (services/autopass.py TRIGGERS).
    trigger: Mapped[str] = mapped_column(String, nullable=False)
    # Only meaningful for trigger="from_player" (nullable otherwise).
    trigger_player_id: Mapped[str | None] = mapped_column(
        UUID(as_uuid=True), ForeignKey("players.id", ondelete="SET NULL")
    )
    target_player_id: Mapped[str] = mapped_column(
        UUID(as_uuid=True), ForeignKey("players.id", ondelete="CASCADE"), nullable=False
    )
    active: Mapped[bool] = mapped_column(
        Boolean, nullable=False, default=True, server_default=text("true")
    )
    created_at: Mapped[datetime.datetime] = created_at()
