from __future__ import annotations

"""Runtime validation utilities for enforcing licence constraints."""

from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path

from .license_manager import LicenceError, LicenceInfo, LicenceManager


@dataclass
class LicenceStatus:
    info: LicenceInfo
    expires_in_days: float
    grace_remaining_hours: float


class LicenceValidator:
    def __init__(self, licence_path: Path, hardware_fingerprint: str = ""):
        self.manager = LicenceManager(licence_path)
        self.hardware_fingerprint = hardware_fingerprint
        self.status: LicenceStatus | None = None

    def refresh(self) -> LicenceStatus:
        info = self.manager.load(self.hardware_fingerprint)
        now = datetime.now(timezone.utc)
        expires_in = (info.valid_until - now).total_seconds() / 86400
        grace_remaining = info.grace_period_hours
        self.status = LicenceStatus(info, expires_in, grace_remaining)
        return self.status

    def require_feature(self, feature: str) -> None:
        if not self.status:
            raise LicenceError("Licence not loaded.")
        if not self.status.info.features.get(feature, False):
            raise LicenceError(f"Feature '{feature}' not permitted by licence.")
