"""Telemetry module for Nogic CLI — sends events to backend telemetry endpoints."""

import hashlib
import json
import os
import platform
from pathlib import Path

import httpx

from nogic import __version__
from .config import GLOBAL_CONFIG_DIR, CONFIG_FILE

_client: httpx.Client | None = None
_disabled: bool = False


def _get_api_url() -> str:
    """Get the backend API URL from config."""
    from .config import Config

    config = Config.load()
    return config.api_url


def _get_anonymous_id() -> str:
    """Get anonymous ID based on API key (if logged in) or machine."""
    from .config import Config

    config = Config.load()

    if config.api_key:
        return hashlib.sha256(config.api_key.encode()).hexdigest()[:16]

    try:
        login = os.getlogin()
    except OSError:
        login = os.getenv("USER", os.getenv("USERNAME", "unknown"))
    machine_info = f"{platform.node()}-{platform.machine()}-{login}"
    return hashlib.sha256(machine_info.encode()).hexdigest()[:16]


def _is_telemetry_enabled() -> bool:
    """Check if telemetry is enabled (opt-out via env var or config)."""
    if os.getenv("NOGIC_TELEMETRY_DISABLED", "").lower() in ("1", "true", "yes"):
        return False
    if os.getenv("DO_NOT_TRACK", "").lower() in ("1", "true", "yes"):
        return False

    config_file = GLOBAL_CONFIG_DIR / CONFIG_FILE
    if config_file.exists():
        try:
            with open(config_file, encoding="utf-8") as f:
                data = json.load(f)
                if data.get("telemetry_enabled") is False:
                    return False
        except (json.JSONDecodeError, OSError):
            pass
    return True


def _get_client() -> httpx.Client | None:
    """Get or create the httpx client. Returns None if telemetry is disabled."""
    global _client, _disabled
    if _disabled:
        return None

    if not _is_telemetry_enabled():
        _disabled = True
        return None

    if _client is None:
        _client = httpx.Client(timeout=5.0)

    return _client


def capture(event: str, properties: dict | None = None):
    """Capture a telemetry event by sending it to the backend."""
    client = _get_client()
    if client is None:
        return

    try:
        props = properties or {}
        props.update({
            "cli_version": __version__,
            "os": platform.system(),
            "os_version": platform.release(),
            "python_version": platform.python_version(),
        })

        api_url = _get_api_url()
        client.post(
            f"{api_url}/v1/telemetry",
            json={
                "event": event,
                "properties": props,
                "anonymous_id": _get_anonymous_id(),
            },
        )
    except Exception:
        pass


def identify(user_id: str | None = None, properties: dict | None = None):
    """Identify a user by sending to the backend."""
    client = _get_client()
    if client is None:
        return

    if not user_id:
        return

    try:
        hashed_user_id = hashlib.sha256(user_id.encode()).hexdigest()[:16]

        props = properties or {}
        props.update({"os": platform.system()})

        api_url = _get_api_url()
        client.post(
            f"{api_url}/v1/telemetry/identify",
            json={
                "anonymous_id": _get_anonymous_id(),
                "user_id": hashed_user_id,
                "properties": props,
            },
        )
    except Exception:
        pass


def shutdown():
    """Close the HTTP client."""
    global _client
    if _client is not None:
        try:
            _client.close()
        except Exception:
            pass
        _client = None
