import uuid
from datetime import datetime
from typing import Any, Optional
from pydantic import BaseModel, Field


class JSONRPCRequest(BaseModel):
    jsonrpc: str = Field(default="2.0")
    id: Optional[Any] = None
    method: str
    params: Optional[dict[str, Any]] = None


class RegisterMCPServerRequest(BaseModel):
    name: str = Field(min_length=2, max_length=100)
    slug: str = Field(min_length=2, max_length=100)
    transport_type: str = Field(default="http")  # http | sse
    endpoint_url: str = Field(min_length=10, max_length=512)
    auth_token: Optional[str] = None


class MCPServerResponse(BaseModel):
    id: uuid.UUID
    tenant_id: uuid.UUID
    name: str
    slug: str
    transport_type: str
    endpoint_url: str
    is_active: bool
    status: str
    discovered_tools_count: int
    discovered_tools: list[dict[str, Any]]
    last_synced_at: Optional[datetime]
    created_at: datetime


class UpdateToolPolicyRequest(BaseModel):
    is_enabled: bool = True
    requires_approval: bool = False
    rate_limit_per_minute: int = Field(default=60, ge=1, le=1000)
    allowed_roles: list[str] = Field(default_factory=lambda: ["owner", "admin", "editor"])


class ToolPolicyResponse(BaseModel):
    id: uuid.UUID
    tenant_id: uuid.UUID
    tool_name: str
    is_enabled: bool
    requires_approval: bool
    rate_limit_per_minute: int
    allowed_roles: list[str]
    created_at: datetime
    updated_at: datetime


class MCPExecutionLogResponse(BaseModel):
    id: uuid.UUID
    tenant_id: uuid.UUID
    server_id: Optional[uuid.UUID]
    tool_name: str
    caller_type: str
    caller_identity: str
    input_arguments: dict[str, Any]
    output_result: Optional[dict[str, Any]]
    status: str
    execution_time_ms: int
    approval_status: str
    approver_user_id: Optional[uuid.UUID]
    error_message: Optional[str]
    created_at: datetime


class ToolDefinitionResponse(BaseModel):
    name: str
    description: str
    input_schema: dict[str, Any]
    is_dangerous: bool
    source: str  # "platform_core" | "external_server"
    requires_approval: bool
    is_enabled: bool
