"""Tests for CLI PostHog analytics."""

from __future__ import annotations

import importlib
import threading
import time
from pathlib import Path


def _reload_analytics_module():
    import terminaluse.lib.cli.analytics as analytics

    return importlib.reload(analytics)


def _set_temp_credentials_root(monkeypatch, analytics, tmp_path: Path) -> None:
    monkeypatch.setattr(analytics, "get_credentials_path", lambda: tmp_path / "credentials.json")


def test_parse_cli_command_extracts_command_and_flags():
    analytics = _reload_analytics_module()

    command, flags = analytics.parse_cli_command(["--debug", "tasks", "send", "task_123", "-m", "hello"])

    assert command == "tasks.send"
    assert "--debug" in flags
    assert "-m" in flags


def test_parse_cli_command_handles_version():
    analytics = _reload_analytics_module()

    command, flags = analytics.parse_cli_command(["--version"])

    assert command == "version"
    assert "--version" in flags


def test_parse_cli_command_does_not_treat_command_level_v_as_version():
    analytics = _reload_analytics_module()

    command, flags = analytics.parse_cli_command(["tasks", "send", "-v"])

    assert command == "tasks.send"
    assert "-v" in flags


def test_init_cli_analytics_enabled_by_default(monkeypatch, tmp_path):
    monkeypatch.delenv("DO_NOT_TRACK", raising=False)

    analytics = _reload_analytics_module()
    _set_temp_credentials_root(monkeypatch, analytics, tmp_path)

    assert analytics.init_cli_analytics(service_version="1.2.3") is True


def test_track_cli_command_posts_event(monkeypatch, tmp_path):
    monkeypatch.delenv("DO_NOT_TRACK", raising=False)

    analytics = _reload_analytics_module()
    _set_temp_credentials_root(monkeypatch, analytics, tmp_path)

    captured: dict = {}
    posted = threading.Event()

    def fake_post(url, json, timeout):  # noqa: ANN001
        captured["url"] = url
        captured["json"] = json
        captured["timeout"] = timeout
        posted.set()
        return object()

    monkeypatch.setattr(analytics.httpx, "post", fake_post)

    assert analytics.init_cli_analytics(service_version="9.9.9") is True
    analytics.track_cli_command(
        command="deploy",
        exit_code=0,
        duration_ms=128,
        flags=["--debug"],
        run_id="run-1",
    )

    assert posted.wait(1), "expected async PostHog capture"
    assert captured["url"] == "https://us.i.posthog.com/capture/"
    payload = captured["json"]
    assert payload["api_key"] == analytics._POSTHOG_PROJECT_API_KEY
    assert payload["event"] == "cli_command_completed"
    assert payload["properties"]["cli.command"] == "deploy"
    assert payload["properties"]["cli.success"] is True
    assert payload["properties"]["cli.version"] == "9.9.9"
    assert payload["properties"]["cli.run_id"] == "run-1"


def test_track_cli_command_started_posts_event(monkeypatch, tmp_path):
    monkeypatch.delenv("DO_NOT_TRACK", raising=False)

    analytics = _reload_analytics_module()
    _set_temp_credentials_root(monkeypatch, analytics, tmp_path)

    captured: dict = {}
    posted = threading.Event()

    def fake_post(url, json, timeout):  # noqa: ANN001
        captured["url"] = url
        captured["json"] = json
        captured["timeout"] = timeout
        posted.set()
        return object()

    monkeypatch.setattr(analytics.httpx, "post", fake_post)

    assert analytics.init_cli_analytics(service_version="9.9.9") is True
    analytics.track_cli_command_started(
        command="tasks.send",
        flags=["--debug"],
        run_id="run-2",
        help_requested=True,
    )

    assert posted.wait(1), "expected async PostHog capture"
    payload = captured["json"]
    assert payload["event"] == "cli_command_started"
    assert payload["properties"]["cli.command"] == "tasks.send"
    assert payload["properties"]["cli.help_requested"] is True
    assert payload["properties"]["cli.run_id"] == "run-2"
    assert payload["properties"]["cli.session_id"] is not None
    assert payload["properties"]["cli.command_index"] >= 1


def test_actor_type_explicit_override(monkeypatch, tmp_path):
    monkeypatch.delenv("DO_NOT_TRACK", raising=False)
    monkeypatch.setenv("TU_ACTOR_TYPE", "agent")

    analytics = _reload_analytics_module()
    _set_temp_credentials_root(monkeypatch, analytics, tmp_path)

    captured: dict = {}
    posted = threading.Event()

    def fake_post(url, json, timeout):  # noqa: ANN001
        captured["json"] = json
        posted.set()
        return object()

    monkeypatch.setattr(analytics.httpx, "post", fake_post)

    assert analytics.init_cli_analytics(service_version="9.9.9") is True
    analytics.track_cli_command(command="deploy", exit_code=0, duration_ms=10)

    assert posted.wait(1), "expected async PostHog capture"
    payload = captured["json"]
    assert payload["properties"]["actor.type"] == "agent"
    assert payload["properties"]["actor.source"] == "explicit_env"


def test_actor_type_ci_from_jenkins_url(monkeypatch, tmp_path):
    monkeypatch.delenv("DO_NOT_TRACK", raising=False)
    monkeypatch.delenv("CI", raising=False)
    monkeypatch.setenv("JENKINS_URL", "https://jenkins.example.com/")

    analytics = _reload_analytics_module()
    _set_temp_credentials_root(monkeypatch, analytics, tmp_path)

    captured: dict = {}
    posted = threading.Event()

    def fake_post(url, json, timeout):  # noqa: ANN001
        captured["json"] = json
        posted.set()
        return object()

    monkeypatch.setattr(analytics.httpx, "post", fake_post)

    assert analytics.init_cli_analytics(service_version="9.9.9") is True
    analytics.track_cli_command(command="deploy", exit_code=0, duration_ms=10)

    assert posted.wait(1), "expected async PostHog capture"
    payload = captured["json"]
    assert payload["properties"]["actor.type"] == "ci"
    assert payload["properties"]["actor.source"] == "ci_env"


def test_track_cli_command_non_blocking(monkeypatch, tmp_path):
    monkeypatch.delenv("DO_NOT_TRACK", raising=False)

    analytics = _reload_analytics_module()
    _set_temp_credentials_root(monkeypatch, analytics, tmp_path)

    posted = threading.Event()

    def fake_post(url, json, timeout):  # noqa: ANN001
        time.sleep(0.25)
        posted.set()
        return object()

    monkeypatch.setattr(analytics.httpx, "post", fake_post)

    assert analytics.init_cli_analytics(service_version="9.9.9") is True

    start = time.monotonic()
    analytics.track_cli_command(command="deploy", exit_code=0, duration_ms=10)
    elapsed = time.monotonic() - start

    assert elapsed < 0.1
    assert posted.wait(1), "expected async PostHog capture"


def test_track_cli_command_respects_opt_out(monkeypatch, tmp_path):
    monkeypatch.setenv("DO_NOT_TRACK", "1")

    analytics = _reload_analytics_module()
    _set_temp_credentials_root(monkeypatch, analytics, tmp_path)

    called = False

    def fake_post(url, json, timeout):  # noqa: ANN001
        nonlocal called
        called = True
        return object()

    monkeypatch.setattr(analytics.httpx, "post", fake_post)

    assert analytics.init_cli_analytics(service_version="9.9.9") is False
    analytics.track_cli_command(
        command="deploy",
        exit_code=0,
        duration_ms=128,
    )

    assert called is False
