"""Lightweight, anonymous telemetry for StableStack.

Collects only:
- stablestack version
- Python version
- platform/arch
- command run (check/activate/status)
- number of findings by severity
- number of files scanned

Never collects:
- source code or file contents
- file paths or names
- finding details or messages
- IP addresses (not logged server-side)

Respects:
- DO_NOT_TRACK=1 environment variable
- STABLESTACK_NO_TELEMETRY=1 environment variable
- --no-telemetry CLI flag

Telemetry is fire-and-forget in a background thread.
Failures are silently ignored — never affects CLI performance.
"""

import json
import os
import platform
import sys
import threading
import urllib.request

TELEMETRY_ENDPOINT = "https://api.stablestack.ai/v1/telemetry"
TIMEOUT_SECONDS = 2


def is_telemetry_enabled() -> bool:
    """Check if telemetry is enabled (opt-out via env vars)."""
    if os.environ.get("DO_NOT_TRACK", "").strip() == "1":
        return False
    if os.environ.get("STABLESTACK_NO_TELEMETRY", "").strip() == "1":
        return False
    return True


def send_event(
    command: str,
    *,
    files_scanned: int = 0,
    errors: int = 0,
    warnings: int = 0,
    infos: int = 0,
    checkers_loaded: int = 0,
    is_licensed: bool = False,
) -> None:
    """Send an anonymous telemetry event in a background thread.

    This is fire-and-forget — failures are silently ignored.
    """
    if not is_telemetry_enabled():
        return

    payload = {
        "v": 1,
        "tool_version": _get_version(),
        "python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
        "platform": sys.platform,
        "arch": platform.machine(),
        "command": command,
        "files_scanned": files_scanned,
        "errors": errors,
        "warnings": warnings,
        "infos": infos,
        "checkers_loaded": checkers_loaded,
        "is_licensed": is_licensed,
    }

    thread = threading.Thread(target=_send, args=(payload,), daemon=True)
    thread.start()


def _get_version() -> str:
    try:
        from stablestack import __version__
        return __version__
    except Exception:
        return "unknown"


def _send(payload: dict) -> None:
    """Send the payload to the telemetry endpoint. Silently fails."""
    try:
        data = json.dumps(payload).encode("utf-8")
        req = urllib.request.Request(
            TELEMETRY_ENDPOINT,
            data=data,
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        urllib.request.urlopen(req, timeout=TIMEOUT_SECONDS)
    except Exception:
        pass  # Never fail the CLI for telemetry
