"""Telemetry — Sentry opt-in for anonymous crash reporting."""

from __future__ import annotations

from pathlib import Path

from ievo.core.global_config import get_config, set_config
from ievo.utils.console import info, success

CLI_SENTRY_DSN = (
    "https://09d4c54e8ac3b9cc79efea50bf635efb@o4510962988482560.ingest.us.sentry.io"
    "/4510963845758976"
)

_sentry_initialized = False


def is_telemetry_enabled(home: Path) -> bool:
    """Check if telemetry is enabled in config."""
    return get_config(home, "telemetry") is True


def prompt_telemetry(home: Path) -> bool:
    """Ask user if they want to enable anonymous crash reporting.

    Returns True if opted in.
    """
    info("[bold]Help improve iEvo[/bold]")
    info("Send anonymous crash reports to help us find and fix bugs?")
    info("[dim]No personal data, code, or agent content is ever sent.[/dim]")

    answer = input("  Enable telemetry? (y/N): ").strip().lower()
    enabled = answer in ("y", "yes")

    set_config(home, "telemetry", enabled)

    if enabled:
        success("Telemetry enabled. Thank you!")
    else:
        info(
            "Telemetry disabled. You can enable it later with "
            "[bold]ievo config set telemetry true[/bold]."
        )

    return enabled


def init_sentry(home: Path) -> bool:
    """Initialize Sentry if telemetry is enabled.

    Returns True if Sentry was initialized.
    Safe to call multiple times — only initializes once.
    """
    global _sentry_initialized  # noqa: PLW0603

    if _sentry_initialized:
        return True

    if not is_telemetry_enabled(home):
        return False

    try:
        import sentry_sdk
    except ImportError:
        return False

    from ievo import __version__

    sentry_sdk.init(
        dsn=CLI_SENTRY_DSN,
        release=f"ievo@{__version__}",
        environment="cli",
        traces_sample_rate=0,
        send_default_pii=False,
    )
    _sentry_initialized = True
    return True


def reset_sentry_state() -> None:
    """Reset initialization state. For testing only."""
    global _sentry_initialized  # noqa: PLW0603
    _sentry_initialized = False
