"""Tests for telemetry module."""
import hashlib
from unittest.mock import MagicMock, patch

import pytest

from surfinguard._telemetry import _sha256, report_telemetry
from surfinguard.models import CheckResult


def test_sha256_produces_64_char_hex():
    result = _sha256("https://example.com")
    assert len(result) == 64
    assert all(c in "0123456789abcdef" for c in result)


def test_sha256_consistent():
    assert _sha256("test-input") == _sha256("test-input")


def test_sha256_different_inputs():
    assert _sha256("input-a") != _sha256("input-b")


def test_sha256_matches_hashlib():
    value = "https://evil.com/phishing"
    expected = hashlib.sha256(value.encode("utf-8")).hexdigest()
    assert _sha256(value) == expected


def test_report_telemetry_sends_hashed_value():
    mock_http = MagicMock()
    result = CheckResult(score=8, level="DANGER", allow=False, reasons=["Phishing domain"])

    report_telemetry(mock_http, "url", "https://evil.com", result, "0.9.0")

    mock_http.post.assert_called_once()
    path, body = mock_http.post.call_args[0]
    assert path == "/v2/telemetry"
    assert body["action_type"] == "url"
    assert len(body["value_hash"]) == 64
    assert "evil.com" not in body["value_hash"]
    assert body["score"] == 8
    assert body["sdk_version"] == "0.9.0"


def test_report_telemetry_swallows_errors():
    mock_http = MagicMock()
    mock_http.post.side_effect = Exception("Network error")
    result = CheckResult(score=5, level="CAUTION", allow=True, reasons=[])

    # Should not raise
    report_telemetry(mock_http, "url", "test", result, "0.9.0")
