"""Pydantic models for the mesh credential vault."""
from __future__ import annotations

from datetime import datetime
from enum import Enum
from typing import Dict, List, Optional

from pydantic import BaseModel, Field


# ── Enums ────────────────────────────────────────────────────────────────────

class CredentialScope(str, Enum):
    GLOBAL = "global"          # Available to all nodes
    CONTROLLER = "controller"  # Controller only
    NODE = "node"              # Specific node(s)
    SERVICE = "service"        # Specific service type


class CloudProvider(str, Enum):
    AWS = "aws"
    GCP = "gcp"
    AZURE = "azure"
    DOCKER = "docker"
    GITHUB = "github"
    CUSTOM = "custom"


class ServiceRequirement(str, Enum):
    """What mesh service needs this credential."""
    JOB_EXECUTION = "job_execution"
    MODEL_STORAGE = "model_storage"
    TELEMETRY = "telemetry"
    IMAGE_REGISTRY = "image_registry"
    SOURCE_CONTROL = "source_control"
    ATLAS_BACKUP = "atlas_backup"
    LICENSE_SERVER = "license_server"
    UPDATE_SERVER = "update_server"
    NOTIFICATION = "notification"
    CUSTOM = "custom"


# ── Credential Models ────────────────────────────────────────────────────────

class CredentialEntry(BaseModel):
    credential_id: str
    name: str
    provider: CloudProvider
    service: ServiceRequirement
    scope: CredentialScope
    allowed_nodes: List[str] = Field(default_factory=list)
    fields: Dict[str, str] = Field(default_factory=dict)
    created_at: datetime
    updated_at: datetime
    last_accessed: Optional[datetime] = None
    access_count: int = 0
    expires_at: Optional[datetime] = None


class CredentialRequest(BaseModel):
    name: str
    provider: CloudProvider
    service: ServiceRequirement
    scope: CredentialScope = CredentialScope.GLOBAL
    allowed_nodes: List[str] = Field(default_factory=list)
    fields: Dict[str, str]
    expires_at: Optional[datetime] = None


class CredentialGrant(BaseModel):
    """What a node receives -- a scoped, time-limited view of a credential."""
    grant_id: str
    credential_id: str
    provider: CloudProvider
    fields: Dict[str, str]
    expires_at: datetime


class VaultStatus(BaseModel):
    sealed: bool
    credential_count: int
    providers: Dict[str, int] = Field(default_factory=dict)
    last_access: Optional[datetime] = None


class AccessPolicy(BaseModel):
    """Per-service access requirements and setup guide."""
    provider: CloudProvider
    service: ServiceRequirement
    required_fields: List[str]
    optional_fields: List[str] = Field(default_factory=list)
    required_permissions: List[str]
    description: str
    setup_guide: str
