"""
Support context helpers for g-gremlin CLI.
"""

from __future__ import annotations

import json
import platform
import re
from pathlib import Path
from typing import Any

from g_gremlin import __version__
from g_gremlin.paths import gremlin_path


_SUPPORT_LOG_CANDIDATES = [
    Path(".g_gremlin") / "logs" / "gremlin.log",
    Path(".g_gremlin") / "gremlin.log",
    gremlin_path("logs", "gremlin.log"),
    gremlin_path("gremlin.log"),
]


def _get_provenance_helpers():
    from g_gremlin import provenance as provenance_helpers
    return provenance_helpers


def _redact_text(text: str) -> str:
    """Lightweight redaction for emails/phones in previews."""
    if not text:
        return text
    redacted = re.sub(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+", "<redacted-email>", text)
    redacted = re.sub(r"\b\d{3}[-.\s]?\d{3}[-.\s]?\d{4}\b", "<redacted-phone>", redacted)
    return redacted


def _sanitize_log_line(line: str) -> str:
    if not line:
        return line
    redacted = _redact_text(line)
    patterns = [
        (r"(?i)(bearer\s+)[A-Za-z0-9._-]+", r"\1[REDACTED]"),
        (r"(?i)(authorization\s*[:=]\s*)\S+", r"\1[REDACTED]"),
        (r"(?i)(x-api-key\s*[:=]\s*)\S+", r"\1[REDACTED]"),
        (r"(?i)(api[_-]?key\s*[:=]\s*)\S+", r"\1[REDACTED]"),
        (r"(?i)(token\s*[:=]\s*)\S+", r"\1[REDACTED]"),
    ]
    for pattern, replacement in patterns:
        redacted = re.sub(pattern, replacement, redacted)
    return redacted


def _read_support_log_tail(limit: int) -> list[str]:
    if limit <= 0:
        return []
    log_path = next((p for p in _SUPPORT_LOG_CANDIDATES if p.exists()), None)
    if not log_path:
        return []
    try:
        content = log_path.read_text(encoding="utf-8", errors="ignore")
    except Exception:
        return []
    lines = content.splitlines()
    tail = lines[-limit:] if lines else []
    return [_sanitize_log_line(line) for line in tail]


def _load_support_config() -> dict[str, Any] | None:
    try:
        provenance = _get_provenance_helpers()
    except Exception:
        return None
    config_path = getattr(provenance, "CONFIG_PATH", gremlin_path("config.json"))
    if not config_path.exists():
        return None
    try:
        config = json.loads(config_path.read_text(encoding="utf-8"))
    except Exception:
        return None
    try:
        return provenance.sanitize_args(config)
    except Exception:
        return config


def _load_sheet_state_snapshot() -> dict[str, Any] | None:
    state_path = Path(".g_gremlin") / "state.json"
    if not state_path.exists():
        return None
    try:
        data = json.loads(state_path.read_text(encoding="utf-8"))
    except Exception:
        return None
    spreadsheet_id = str(data.get("spreadsheet_id") or "").strip()
    if not spreadsheet_id:
        return None
    snapshot: dict[str, Any] = {
        "spreadsheet_id": spreadsheet_id,
        "range": data.get("range"),
        "output_file": data.get("output_file"),
        "pulled_at": data.get("pulled_at"),
        "sheet_url": f"https://docs.google.com/spreadsheets/d/{spreadsheet_id}",
    }
    return snapshot


def _build_support_context(
    include_logs: bool,
    log_lines: int,
    include_config: bool,
    include_state: bool,
    extra: dict[str, Any] | None = None,
) -> dict[str, Any]:
    context: dict[str, Any] = {
        "client": {
            "name": "g-gremlin",
            "version": __version__,
            "python": platform.python_version(),
            "os": platform.platform(),
        }
    }
    if include_state:
        state = _load_sheet_state_snapshot()
        if state:
            context["sheet_context"] = state
    if include_config:
        config = _load_support_config()
        if config:
            context["config"] = config
    if include_logs:
        tail = _read_support_log_tail(log_lines)
        if tail:
            context["log_tail"] = tail
    if extra:
        context.update(extra)
    return context
