"""Certificate inventory data models — cross-cloud (AWS ACM + Azure Key Vault)."""

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

from pydantic import BaseModel, computed_field


class CertificateStatus(str, Enum):
    ACTIVE = "ACTIVE"
    EXPIRED = "EXPIRED"
    EXPIRING_SOON = "EXPIRING_SOON"
    PENDING = "PENDING"
    UNKNOWN = "UNKNOWN"


class RiskLevel(str, Enum):
    CRITICAL = "CRITICAL"
    HIGH = "HIGH"
    MEDIUM = "MEDIUM"
    LOW = "LOW"
    OK = "OK"


class CertificateRecord(BaseModel):
    """Unified certificate record (AWS ACM, IAM Server Cert, Azure Key Vault)."""

    domain: str
    identifier: str  # ARN (AWS) or resource ID (Azure)
    cloud: str  # "aws" or "azure"
    source: str  # "acm", "iam-server-cert", "key-vault", "app-service", "app-gateway"
    account_or_subscription: str
    region: str
    status: str
    cert_type: str  # AMAZON_ISSUED, IMPORTED, etc.
    issuer: str = "N/A"
    not_after: Optional[datetime] = None
    in_use: bool = False
    used_by: List[str] = []
    renewal_status: str = "N/A"
    key_algorithm: str = "N/A"
    tags: Dict[str, str] = {}

    @computed_field
    @property
    def days_until_expiry(self) -> Optional[int]:
        if self.not_after is None:
            return None
        now = datetime.now(timezone.utc)
        expiry = self.not_after if self.not_after.tzinfo else self.not_after.replace(tzinfo=timezone.utc)
        return (expiry - now).days

    @computed_field
    @property
    def risk_level(self) -> str:
        d = self.days_until_expiry
        if d is None:
            return RiskLevel.OK.value
        if d < 0:
            return RiskLevel.CRITICAL.value if self.in_use else RiskLevel.HIGH.value
        if d <= 30:
            return RiskLevel.CRITICAL.value
        if d <= 60:
            return RiskLevel.HIGH.value
        if d <= 90:
            return RiskLevel.MEDIUM.value
        return RiskLevel.OK.value
