from __future__ import annotations

from datetime import datetime
from typing import Any, Optional
from uuid import UUID

from pydantic import BaseModel, ConfigDict, Field


class EventRegistryItem(BaseModel):
    model_config = ConfigDict(populate_by_name=True)

    name: str
    version: str
    classification: str
    alias: str
    label: str
    json_schema: dict[str, Any] = Field(default_factory=dict, alias="schema")


class IntegrationSubscriptionResponse(BaseModel):
    id: UUID
    workspace_id: UUID
    project_id: UUID
    connection_id: Optional[UUID] = None
    event: str
    event_version: str
    destination: str
    url: Optional[str] = None
    secret_configured: bool = False
    filter_json: dict[str, Any] = Field(default_factory=dict)
    ignore_origin: bool = True
    max_hops: int = 5
    status: str
    created_at: datetime
    updated_at: datetime


class UpsertSubscriptionRequest(BaseModel):
    event: str
    event_version: str = "01.00.00"
    destination: str = "webhook"
    connection_id: Optional[UUID] = None
    url: Optional[str] = None
    secret: Optional[str] = None
    filter_json: dict[str, Any] = Field(default_factory=dict)
    ignore_origin: bool = True
    max_hops: int = 5
    status: str = "active"


class CommandAuthorizeRequest(BaseModel):
    workspace_id: str
    project_id: str
    command: str
    command_id: str
    idempotency_key: str
    environment: str = "production"
    resource: dict[str, Any] = Field(default_factory=dict)
    input: dict[str, Any] = Field(default_factory=dict)
    command_hash: Optional[str] = None
    connection_id: str
    principal_type: str = "integration"
    principal_id: Optional[str] = None
    source_provider: str
    request_id: str
    correlation_id: str
    actor_external_id: Optional[str] = None


class ControlPlaneCommandRequest(BaseModel):
    """User-authorized request for a Core-owned automation command."""

    command: str = Field(min_length=1, max_length=120)
    command_id: str = Field(min_length=1, max_length=120)
    idempotency_key: str = Field(min_length=1, max_length=255)
    workspace_id: Optional[UUID] = None
    project_id: Optional[UUID] = None
    input: dict[str, Any] = Field(default_factory=dict)


class ControlPlaneCommandResponse(BaseModel):
    ok: bool = True
    command: str
    command_id: str
    result: dict[str, Any] = Field(default_factory=dict)
