"""Pydantic v2 models for Hive Mode (GPU pooling).

Hive = friends sharing GPU resources in a private pool.
Pro-tier only. Privacy-tiered routing. Karma system.
"""

from __future__ import annotations

from datetime import datetime  # noqa: TC003 -- Pydantic needs this at runtime
from enum import Enum

from pydantic import BaseModel, Field


class HiveRole(str, Enum):
    """Role of a member in the Hive."""

    OWNER = "owner"
    ADMIN = "admin"
    MEMBER = "member"


class PrivacyTier(str, Enum):
    """Privacy tier for request routing."""

    PRIVATE = "private"  # NEVER leaves owner's machine
    STANDARD = "standard"  # Eligible for Hive routing
    # SENSITIVE (from PII detector) is never shared with Hive; main router/dispatcher force local-only.


class HiveMember(BaseModel):
    """A member of a Hive (friend in the GPU pool)."""

    id: str
    name: str
    email: str | None = None
    role: HiveRole
    joined_at: datetime
    last_seen: datetime | None = None
    devices: list[str] = Field(default_factory=list)  # Device IDs
    karma_score: float = 1.0  # Start at 1.0 (neutral)
    compute_contributed_hours: float = 0.0
    compute_consumed_hours: float = 0.0
    active: bool = True
    # Node sharing controls (persisted in hive.json)
    sharing_enabled: bool = True
    sharing_schedule: str | None = None  # "HH:MM-HH:MM" daily window (e.g. "22:00-08:00")
    shared_models: list[str] = Field(default_factory=list)  # empty = all shareable; else whitelist


class Hive(BaseModel):
    """A Hive group (GPU pooling pool)."""

    id: str
    name: str
    invite_code: str  # Short code for invitations
    owner_id: str
    members: list[HiveMember] = Field(default_factory=list)
    created_at: datetime
    max_members: int = 10  # Pro default
    privacy_default: PrivacyTier = PrivacyTier.STANDARD
    # Headscale coordination plane (Phase 3)
    headscale_user: str | None = None  # Headscale user name (one per Hive)
    headscale_preauth_key: str | None = None  # Pre-auth key for nodes to join the tailnet


class KarmaUpdate(BaseModel):
    """Record of a karma-affecting action."""

    member_id: str
    action: str  # "contributed" or "consumed"
    compute_hours: float
    timestamp: datetime


class HiveInvite(BaseModel):
    """Invitation to join a Hive."""

    hive_id: str
    invite_code: str
    created_by: str
    expires_at: datetime | None = None


class PrivacyClassification(BaseModel):
    """Result of privacy classification for a request."""

    tier: PrivacyTier
    confidence: float
    reasons: list[str] = Field(default_factory=list)  # Why classified this way
    pii_detected: bool = False


class HiveRoutingDecision(BaseModel):
    """Result of Hive-aware routing."""

    use_hive: bool  # Whether to route to Hive (vs local)
    target_member_id: str | None = None
    target_device_id: str | None = None
    privacy_tier: PrivacyTier
    karma_priority: float  # Higher karma = higher priority
    reason: str
