from __future__ import annotations

import uuid
from datetime import UTC, datetime
from typing import Any, Literal

from pydantic import BaseModel, Field

from tracecat.audit.enums import AuditEventActor, AuditEventStatus

AuditAction = Literal["create", "update", "delete", "accept", "revoke"]
AuditResourceType = Literal[
    "user",
    "organization",
    "workspace",
    "workflow",
    "workflow_execution",
    "workspace_variable",
    "tag",
    "table",
    "table_column",
    "organization_setting",
    "secret",
    "organization_secret",
    "case",
    "case_comment",
    "agent_catalog",
    "agent_custom_provider",
    "agent_model_access",
    "agent_preset",
    "agent_session",
    "organization_domain",
    "organization_member",
    "organization_session",
    "organization_invitation",
    "workspace_invitation",
    "service_account",
    "service_account_api_key",
    "mcp_personal_access_token",
    # RBAC resources
    "rbac_scope",
    "rbac_role",
    "rbac_group",
    "rbac_group_member",
    "rbac_assignment",
    "rbac_user_assignment",
]


class AuditEvent(BaseModel):
    organization_id: uuid.UUID | None = None
    """Organization ID. None for platform-level operations (superuser without org context)."""
    workspace_id: uuid.UUID | None = None
    """Workspace ID. None for platform/org-level operations."""
    actor_type: AuditEventActor
    actor_id: uuid.UUID
    actor_label: str | None = None
    ip_address: str | None = None
    resource_type: AuditResourceType
    resource_id: uuid.UUID | None = None
    action: AuditAction
    status: AuditEventStatus
    data: dict[str, Any] | None = None
    created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
