"""Telemetry module — opt-in anonymized check result reporting.

Values are hashed client-side (SHA-256) before being sent;
plaintext values never reach the server.
"""
from __future__ import annotations

import hashlib
import logging
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from ._http import SurfinguardHTTPClient
    from .models import CheckResult

logger = logging.getLogger("surfinguard.telemetry")


def _sha256(value: str) -> str:
    """SHA-256 hash a string and return hex representation."""
    return hashlib.sha256(value.encode("utf-8")).hexdigest()


def report_telemetry(
    http: SurfinguardHTTPClient,
    action_type: str,
    value: str,
    result: CheckResult,
    sdk_version: str,
) -> None:
    """Report a check result as anonymized telemetry.

    Fire-and-forget: errors are silently swallowed.
    """
    try:
        value_hash = _sha256(value)

        primitive: str | None = None
        if result.primitive_scores and len(result.primitive_scores) > 0:
            primitive = result.primitive_scores[0].get("primitive") if isinstance(result.primitive_scores[0], dict) else None

        reasons = (result.reasons or [])[:5]

        http.post("/v2/telemetry", {
            "action_type": action_type,
            "value_hash": value_hash,
            "score": result.score,
            "level": result.level.value if hasattr(result.level, "value") else str(result.level),
            "primitive": primitive,
            "reasons": reasons,
            "threat_ids": getattr(result, "threat_ids", []) or [],
            "sdk_version": sdk_version,
        })
    except Exception:
        # Fire-and-forget: telemetry errors should never block the main flow
        logger.debug("Telemetry report failed (suppressed)", exc_info=True)
