"""Telemetry management commands."""

import json
import os

import typer

from nogic.config import GLOBAL_CONFIG_DIR, CONFIG_FILE
from nogic import ui

telemetry_app = typer.Typer(no_args_is_help=True, rich_markup_mode="rich")


def _load_global_config() -> dict:
    config_path = GLOBAL_CONFIG_DIR / CONFIG_FILE
    if config_path.exists():
        try:
            with open(config_path, encoding="utf-8") as f:
                return json.load(f)
        except (json.JSONDecodeError, OSError):
            return {}
    return {}


def _save_global_config(data: dict):
    GLOBAL_CONFIG_DIR.mkdir(mode=0o700, exist_ok=True)
    config_path = GLOBAL_CONFIG_DIR / CONFIG_FILE
    with open(config_path, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2)
    os.chmod(config_path, 0o600)


@telemetry_app.command("status")
def telemetry_status():
    """Show current telemetry status."""
    config = _load_global_config()
    enabled = config.get("telemetry_enabled", True) is not False

    if enabled:
        ui.success("Telemetry is enabled")
        ui.dim("  Run `nogic telemetry disable` to opt out")
    else:
        ui.warn("Telemetry is disabled")
        ui.dim("  Run `nogic telemetry enable` to enable")

    ui.console.print()
    ui.dim("Telemetry helps us improve Nogic. All data is anonymized.")


@telemetry_app.command("enable")
def telemetry_enable():
    """Enable telemetry."""
    config = _load_global_config()
    config["telemetry_enabled"] = True
    _save_global_config(config)
    ui.success("Telemetry enabled")


@telemetry_app.command("disable")
def telemetry_disable():
    """Disable telemetry."""
    config = _load_global_config()
    config["telemetry_enabled"] = False
    _save_global_config(config)
    ui.success("Telemetry disabled")
