"""
Approval rules define who can approve what tool executions.

Rules are scoped by tool name, risk level, or category, and specify
which users, groups, or roles can approve matching requests.
"""

from sqlalchemy import Column, String, DateTime, Boolean, Integer, JSON, Text, Index, text, desc
from sqlalchemy.dialects.postgresql import UUID
from datetime import datetime

from control_plane_api.app.database import Base


class ApprovalRule(Base):
    """Defines approval requirements for tool executions."""

    __tablename__ = "approval_rules"

    id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
    organization_id = Column(String(255), nullable=False)
    name = Column(String(255), nullable=False)
    description = Column(Text, nullable=True)

    # What this rule covers
    scope_type = Column(String(50), nullable=False)   # 'tool', 'risk_level', 'category', 'all'
    scope_value = Column(String(255), nullable=True)   # e.g. "Bash", "critical", "command_execution"

    # Who can approve
    approver_type = Column(String(50), nullable=False)  # 'user_emails', 'group', 'role'
    approver_value = Column(JSON, nullable=False)        # ["admin@co.com"] or {"group_id": "..."} or {"role": "Admin"}

    # Bypass rules
    auto_approve_roles = Column(JSON, nullable=True, default=list)  # roles that bypass this rule

    # Configuration
    require_reason = Column(Boolean, nullable=False, default=False, server_default=text("false"))
    timeout_minutes = Column(Integer, nullable=False, default=1440, server_default=text("1440"))
    enabled = Column(Boolean, nullable=False, default=True, server_default=text("true"))
    priority = Column(Integer, nullable=False, default=0, server_default=text("0"))

    created_at = Column(DateTime(timezone=False), nullable=True, default=datetime.utcnow, server_default=text("now()"))
    updated_at = Column(DateTime(timezone=False), nullable=True, default=datetime.utcnow, server_default=text("now()"), onupdate=datetime.utcnow)

    __table_args__ = (
        Index('idx_approval_rules_org', 'organization_id'),
        Index('idx_approval_rules_scope', 'scope_type', 'scope_value'),
        Index('idx_approval_rules_enabled', 'enabled'),
        Index('idx_approval_rules_priority', desc('priority')),
        {'schema': 'public'}
    )

    def __repr__(self):
        return f"<ApprovalRule {self.id} name={self.name} scope={self.scope_type}:{self.scope_value}>"
