"""Opt-in CLI telemetry emission for g-gremlin."""

from __future__ import annotations

import base64
import json
import os
import threading
from datetime import datetime, timezone
from typing import Any

from g_gremlin import __version__
from g_gremlin.credentials import license as license_mod


def _telemetry_enabled() -> bool:
    value = os.getenv("G_GREMLIN_TELEMETRY", "").strip().lower()
    return value in ("1", "true", "yes")


def _decode_jwt_payload(token: str) -> dict[str, Any] | None:
    try:
        parts = token.split(".")
        if len(parts) != 3:
            return None
        payload_b64 = parts[1]
        padding = 4 - len(payload_b64) % 4
        if padding != 4:
            payload_b64 += "=" * padding
        payload_json = base64.urlsafe_b64decode(payload_b64)
        return json.loads(payload_json)
    except Exception:
        return None


def _extract_identity(token: str) -> tuple[str | None, str | None]:
    payload = _decode_jwt_payload(token)
    if not payload:
        return None, None
    org_id = (
        payload.get("org_id")
        or payload.get("orgId")
        or payload.get("organization_id")
        or payload.get("organizationId")
    )
    email = payload.get("email") or payload.get("user_email") or payload.get("userEmail")
    return (str(org_id) if org_id else None, str(email) if email else None)


def _support_api_base() -> str:
    """Return base URL for support/telemetry endpoints (FastAPI backend)."""
    base = os.getenv("FOUNDRYOPS_SUPPORT_API_URL") or os.getenv(
        "FOUNDRYGRAPH_API_BASE",
        "https://fuzzy-matcher-api-5pkec6diha-uc.a.run.app",
    )
    return base.rstrip("/")


def _build_event(
    command: str,
    status: str,
    duration_ms: int,
    correlation_id: str,
    exit_code: int,
    org_id: str,
    user_email: str,
    attrs: dict[str, Any] | None = None,
) -> dict[str, Any]:
    action = f"cli.{command.replace(' ', '.') if command else 'unknown'}"
    merged_attrs = {"exit_code": exit_code}
    if attrs:
        merged_attrs.update(attrs)
    event = {
        "ts": datetime.now(timezone.utc).isoformat(),
        "org_id": org_id,
        "user_email": user_email,
        "sheet_id": "cli",
        "source": "g_gremlin_cli",
        "source_version": __version__,
        "action": action,
        "status": status,
        "duration_ms": duration_ms,
        "idempotency_key": correlation_id or f"cli-{os.getpid()}",
        "attrs": merged_attrs,
    }
    return event


def emit_cli_event(
    command: str,
    status: str,
    duration_ms: int,
    correlation_id: str,
    exit_code: int,
    attrs: dict[str, Any] | None = None,
) -> threading.Thread | None:
    if not _telemetry_enabled():
        return None

    token = license_mod.get_license_token()
    if not token:
        return None

    org_id, user_email = _extract_identity(token)
    if not org_id:
        return None

    if not user_email:
        user_email = "cli_user"

    event = _build_event(
        command=command,
        status=status,
        duration_ms=duration_ms,
        correlation_id=correlation_id,
        exit_code=exit_code,
        org_id=org_id,
        user_email=user_email,
        attrs=attrs,
    )

    def _send() -> None:
        try:
            import httpx
        except Exception:
            return
        try:
            url = f"{_support_api_base()}/api/v1/telemetry/events:batch"
            headers = {
                "Authorization": f"Bearer {token}",
                "Content-Type": "application/json",
                "User-Agent": f"g-gremlin/{__version__}",
            }
            httpx.post(url, json={"events": [event]}, headers=headers, timeout=10.0)
        except Exception:
            return

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