from __future__ import annotations

import platform
import socket
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing import Any, Dict, Optional


class ComponentStatus(Enum):
    HEALTHY = "healthy"
    DEGRADED = "degraded"
    UNHEALTHY = "unhealthy"
    UNKNOWN = "unknown"


@dataclass
class AgentMetadata:
    instance_id: str
    instance_name: Optional[str]
    version: str
    started_at: datetime
    hostname: str
    platform: str
    python_version: str

    @classmethod
    def build(cls, instance_id: str, instance_name: Optional[str], version: str) -> "AgentMetadata":
        return cls(
            instance_id=instance_id,
            instance_name=instance_name,
            version=version,
            started_at=datetime.now(timezone.utc),
            hostname=socket.gethostname(),
            platform=platform.system().lower(),
            python_version=platform.python_version(),
        )


@dataclass
class ComponentHealth:
    component: str
    status: ComponentStatus
    last_check: datetime
    last_success: Optional[datetime]
    consecutive_failures: int
    details: Dict[str, Any] = field(default_factory=dict)
    error: Optional[str] = None


@dataclass
class TaskMetrics:
    total_tasks: int
    successful_tasks: int
    failed_tasks: int
    timeout_errors: int
    llm_errors: int
    db_errors: int
    desensitization_errors: int
    avg_execution_time_ms: float
    p95_execution_time_ms: float
    p99_execution_time_ms: float
