"""Tests for anonymous telemetry."""

import json
import os
from unittest.mock import patch

from bilgeai.core.telemetry import (
    TelemetryCollector,
    TelemetryEvent,
    get_telemetry_collector,
    is_telemetry_enabled,
)


class TestIsTelemetryEnabled:
    def test_disabled_by_default(self):
        with patch.dict(os.environ, {}, clear=True):
            assert is_telemetry_enabled() is False

    def test_enabled_with_1(self):
        with patch.dict(os.environ, {"BILGE_TELEMETRY": "1"}):
            assert is_telemetry_enabled() is True

    def test_enabled_with_true(self):
        with patch.dict(os.environ, {"BILGE_TELEMETRY": "true"}):
            assert is_telemetry_enabled() is True

    def test_enabled_with_yes(self):
        with patch.dict(os.environ, {"BILGE_TELEMETRY": "yes"}):
            assert is_telemetry_enabled() is True

    def test_disabled_with_0(self):
        with patch.dict(os.environ, {"BILGE_TELEMETRY": "0"}):
            assert is_telemetry_enabled() is False

    def test_disabled_with_empty(self):
        with patch.dict(os.environ, {"BILGE_TELEMETRY": ""}):
            assert is_telemetry_enabled() is False


class TestTelemetryEvent:
    def test_event_creation(self):
        event = TelemetryEvent(event="command_run", command="profile")
        assert event.event == "command_run"
        assert event.command == "profile"
        assert event.timestamp != ""


class TestTelemetryCollector:
    def test_disabled_does_not_record(self):
        tc = TelemetryCollector(enabled=False)
        tc.record("profile")
        assert len(tc.events) == 0

    def test_enabled_records(self):
        tc = TelemetryCollector(enabled=True)
        tc.record("profile", gpu_vendor="nvidia")
        assert len(tc.events) == 1
        assert tc.events[0].command == "profile"
        assert tc.events[0].gpu_vendor == "nvidia"

    def test_multiple_records(self):
        tc = TelemetryCollector(enabled=True)
        tc.record("profile")
        tc.record("analyze")
        tc.record("run")
        assert len(tc.events) == 3

    def test_session_id_consistent(self):
        tc = TelemetryCollector(enabled=True)
        tc.record("profile")
        tc.record("run")
        assert tc.events[0].session_id == tc.events[1].session_id
        assert tc.events[0].session_id == tc.session_id

    def test_summary_empty(self):
        tc = TelemetryCollector(enabled=True)
        summary = tc.get_summary()
        assert summary["total_events"] == 0

    def test_summary_with_events(self):
        tc = TelemetryCollector(enabled=True)
        tc.record("profile")
        tc.record("profile")
        tc.record("run")
        summary = tc.get_summary()
        assert summary["total_events"] == 3
        assert summary["commands"]["profile"] == 2
        assert summary["commands"]["run"] == 1

    def test_save_disabled_no_file(self, tmp_path):
        tc = TelemetryCollector(enabled=False)
        tc.record("profile")  # won't record since disabled
        path = tmp_path / "telemetry.json"
        tc.save(path)
        assert not path.exists()

    def test_save_enabled(self, tmp_path):
        tc = TelemetryCollector(enabled=True)
        tc.record("profile")
        path = tmp_path / "telemetry.json"
        tc.save(path)
        assert path.exists()
        data = json.loads(path.read_text())
        assert len(data) == 1
        assert data[0]["command"] == "profile"

    def test_save_appends(self, tmp_path):
        path = tmp_path / "telemetry.json"
        path.write_text('[{"event": "old"}]')

        tc = TelemetryCollector(enabled=True)
        tc.record("run")
        tc.save(path)

        data = json.loads(path.read_text())
        assert len(data) == 2


class TestGetTelemetryCollector:
    def test_disabled_by_default(self):
        with patch.dict(os.environ, {}, clear=True):
            tc = get_telemetry_collector()
            assert tc.enabled is False

    def test_enabled_via_env(self):
        with patch.dict(os.environ, {"BILGE_TELEMETRY": "1"}):
            tc = get_telemetry_collector()
            assert tc.enabled is True
