"""First-run consent and anonymous usage telemetry for StackSage.

On first run of `stacksage scan`, the user is prompted once:
  "Send anonymous usage stats to help improve StackSage? (yes/no)"

If yes, sends ONLY:
  { "findings_count": 94, "aws_region_count": 3 }

No resource IDs, no account IDs, no IP addresses, nothing identifiable.
Consent is stored in ~/.stacksage/config.json and never asked again.

Telemetry is fire-and-forget — any failure is silently swallowed.
A scan must never fail because of a telemetry error.
"""

from __future__ import annotations

import json
import logging
from pathlib import Path
from typing import Any, Dict

logger = logging.getLogger(__name__)

_CONFIG_DIR = Path.home() / ".stacksage"
_CONFIG_FILE = _CONFIG_DIR / "config.json"
_TELEMETRY_ENDPOINT = "https://telemetry.stacksageai.com/v1/ping"

_CONSENT_KEY = "usage_stats_consent"
_FIRST_RUN_KEY = "first_run_complete"


def _load_config() -> Dict[str, Any]:
    if _CONFIG_FILE.exists():
        try:
            with open(_CONFIG_FILE) as f:
                return json.load(f)
        except Exception:
            return {}
    return {}


def _save_config(config: Dict[str, Any]) -> None:
    try:
        _CONFIG_DIR.mkdir(parents=True, exist_ok=True)
        with open(_CONFIG_FILE, "w") as f:
            json.dump(config, f, indent=2)
    except Exception as e:
        logger.debug("Could not save telemetry config: %s", e)


def check_and_prompt_consent() -> bool:
    """Prompt for telemetry consent on first run.

    Returns True if the user consented (now or previously), False otherwise.
    Consent is persisted — the prompt is shown at most once ever.
    """
    config = _load_config()

    # Already decided — honour previous choice
    if _CONSENT_KEY in config:
        return bool(config[_CONSENT_KEY])

    # First run — ask
    print()
    print("─" * 60)
    print("StackSage can send anonymous usage stats to help improve")
    print("the tool. This sends ONLY:")
    print("  • Number of findings found")
    print("  • Number of AWS regions scanned")
    print("No resource IDs, account IDs, or any identifiable data.")
    print("─" * 60)

    try:
        answer = input("Send anonymous usage stats? (yes/no): ").strip().lower()
    except (EOFError, KeyboardInterrupt):
        answer = "no"

    consent = answer in ("yes", "y")
    config[_CONSENT_KEY] = consent
    config[_FIRST_RUN_KEY] = True
    _save_config(config)

    if consent:
        print("Thanks! Edit ~/.stacksage/config.json to change this at any time.")
    else:
        print("No stats will be sent. Edit ~/.stacksage/config.json to change this.")
    print()

    return consent


def send_anonymous_ping(findings_count: int, region_count: int) -> None:
    """Fire-and-forget POST with minimal anonymous telemetry.

    Silently swallows ALL errors — telemetry must never interrupt a scan.
    """
    try:
        import urllib.request

        payload = json.dumps(
            {"findings_count": findings_count, "aws_region_count": region_count}
        ).encode("utf-8")
        req = urllib.request.Request(
            _TELEMETRY_ENDPOINT,
            data=payload,
            headers={
                "Content-Type": "application/json",
                "User-Agent": "stacksage-cli/0.7.2",
            },
            method="POST",
        )
        urllib.request.urlopen(req, timeout=3)
    except Exception as e:
        logger.debug("Telemetry ping failed (non-fatal): %s", e)
