"""Pydantic schemas for approval rules API."""

from typing import Optional, List, Any, Dict, Literal
from pydantic import BaseModel, Field


class ApprovalRuleCreate(BaseModel):
    """Request model for creating an approval rule.

    approver_type + approver_value formats:
      - "user_emails": ["admin@co.com", "ops@co.com"]
      - "group": {"group_uuid": "...", "group_name": "Admin", "emails": ["admin@co.com"]}
            The frontend resolves group members and stores their emails at rule creation time.

    auto_approve_groups: List of Kubiya group **names** (e.g. ["Admin"]).
        If the requesting user is a member of any listed group, the tool is auto-approved.
        Group names come from the Kubiya user_groups API.
    """
    name: str = Field(..., min_length=1, max_length=255)
    description: Optional[str] = None
    scope_type: Literal["tool", "risk_level", "category", "all"]
    scope_value: Optional[str] = None
    approver_type: Literal["user_emails", "group"]
    approver_value: Any  # List[str] for emails, dict for group
    auto_approve_roles: Optional[List[str]] = Field(
        default_factory=list,
        description="Kubiya group names that bypass this rule (e.g. ['Admin'])",
    )
    require_reason: bool = False
    timeout_minutes: int = Field(default=1440, ge=1, le=43200)
    enabled: bool = True
    priority: int = Field(default=0, ge=0)


class ApprovalRuleUpdate(BaseModel):
    """Request model for updating an approval rule."""
    name: Optional[str] = Field(None, min_length=1, max_length=255)
    description: Optional[str] = None
    scope_type: Optional[Literal["tool", "risk_level", "category", "all"]] = None
    scope_value: Optional[str] = None
    approver_type: Optional[Literal["user_emails", "group"]] = None
    approver_value: Optional[Any] = None
    auto_approve_roles: Optional[List[str]] = None
    require_reason: Optional[bool] = None
    timeout_minutes: Optional[int] = Field(None, ge=1, le=43200)
    enabled: Optional[bool] = None
    priority: Optional[int] = Field(None, ge=0)


class ApprovalRuleResponse(BaseModel):
    """Response model for an approval rule."""
    id: str
    organization_id: str
    name: str
    description: Optional[str] = None
    scope_type: str
    scope_value: Optional[str] = None
    approver_type: str
    approver_value: Any
    auto_approve_roles: Optional[List[str]] = None
    require_reason: bool
    timeout_minutes: int
    enabled: bool
    priority: int
    created_at: Optional[str] = None
    updated_at: Optional[str] = None

    model_config = {"from_attributes": True}


class ResolveApprovalRuleRequest(BaseModel):
    """Request to resolve which approval rule matches a tool context.

    Note: user_groups is NOT sent by the client. The backend resolves it
    from the authenticated user's Kubiya profile (request.state.organization["user_groups"]).
    """
    tool_name: str
    tool_args: Optional[Dict[str, Any]] = None
    risk_level: Optional[str] = None
    category: Optional[str] = None


class ResolveApprovalRuleResponse(BaseModel):
    """Response with the matching approval rule and approvers."""
    rule_id: Optional[str] = None
    rule_name: Optional[str] = None
    rule: Optional[ApprovalRuleResponse] = None
    approver_emails: List[str] = Field(default_factory=list)
    auto_approved: bool = False
    require_reason: bool = False
    timeout_minutes: int = 1440
    message: str
