"""
Error tracking for QA Copilot (Roadmap 5.2).

Sends error events to Sentry via HTTP API (no SDK dependency).
No-op when QA_SENTRY_DSN is not configured.
"""
from __future__ import annotations

import json
import os
import threading
import traceback
import urllib.request
import urllib.error

_dsn = os.environ.get("QA_SENTRY_DSN", "")
_initialized = False
_project_id = ""
_public_key = ""
_host = ""


def init() -> None:
    """Initialize error tracking from QA_SENTRY_DSN. No-op if not set."""
    global _initialized, _project_id, _public_key, _host
    if not _dsn:
        return
    try:
        # Parse DSN: https://<public_key>@<host>/<project_id>
        parts = _dsn.replace("https://", "").split("@")
        _public_key = parts[0]
        host_and_project = parts[1].rsplit("/", 1)
        _host = host_and_project[0]
        _project_id = host_and_project[1]
        _initialized = True
        print(f"  ✓ Sentry initialized (project {_project_id})")
    except Exception as e:
        print(f"  ⚠  Sentry DSN parse failed: {e}")


def capture_exception(exc: Exception) -> None:
    """Send exception to Sentry. No-op if not initialized."""
    if not _initialized:
        return
    def _send():
        try:
            tb = traceback.format_exception(type(exc), exc, exc.__traceback__)
            payload = {
                "exception": {
                    "values": [{
                        "type": type(exc).__name__,
                        "value": str(exc),
                        "stacktrace": {"frames": [{"filename": "server.py", "function": "handler", "raw": "".join(tb)}]},
                    }]
                },
                "platform": "python",
                "level": "error",
            }
            url = f"https://{_host}/api/{_project_id}/store/"
            req = urllib.request.Request(
                url,
                data=json.dumps(payload).encode(),
                headers={
                    "Content-Type": "application/json",
                    "X-Sentry-Auth": f"Sentry sentry_version=7, sentry_key={_public_key}",
                },
                method="POST",
            )
            urllib.request.urlopen(req, timeout=5)
        except Exception:
            pass
    threading.Thread(target=_send, daemon=True).start()


def set_user(user_dict: dict) -> None:
    """Set user context for future events. Currently a no-op placeholder
    (HTTP API events are stateless; user info would be added per-event)."""
    pass


def is_configured() -> bool:
    return _initialized
