"""THE GROQ ADAPTER — real generated text, gated by the vault, never invented.

Why this file exists
--------------------
Every other adapter in this app measures something the world already said: a
forecast, a business count, a price. Groq is the first adapter that *writes*:
it asks a hosted open model for a draft and reports exactly what came back.

The same contract as the keyless adapters
-----------------------------------------
The result shape is the one ``open_meteo`` and ``overpass`` already use —
``status``, ``reason``, ``http_code``, ``rows``, ``columns``, ``signals``,
``source_url``, ``error``, ``generated_at`` — and the status vocabulary is the
same two honest values:

    HTTP 200 + parseable JSON   -> "OK"        real generated text
    any other HTTP status       -> "DEGRADED"  literal "HTTP <code>: <body>" reason
    timeout / DNS / TLS         -> "DEGRADED"  literal "<ExceptionType>: <text>"
    200 but unparseable         -> "DEGRADED"  "HTTP 200 but the body did not parse: ..."
    no credential               -> "DEGRADED"  "GROQ_API_KEY not set — no request sent"

On every non-OK status the result carries ``text == ""``, ``rows == []`` and
``signals == []`` — the live-data bridge turns that into ZERO claims. A draft we
could not generate is reported as unavailable, never guessed.

No credential, no request
-------------------------
``secrets_vault.get("GROQ_API_KEY")`` (environment first, then the vault file)
decides whether a request happens at all. With no key there is nothing to
authenticate with, so the adapter sends nothing and says so literally. The live
probe is the same: a missing key is a DEGRADED result with no HTTP status
because there was no HTTP call.

Transport
---------
``POST https://api.groq.com/openai/v1/chat/completions`` with
``Authorization: Bearer <key>`` and ``model = "openai/gpt-oss-120b"``. Every
attempt has a hard ``TIMEOUT_SECONDS`` ceiling; an HTTP 429 is retried with
exponential backoff (``RETRY_BACKOFF_SECONDS``, doubled, capped) up to
``MAX_ATTEMPTS``. Any other non-200 is recorded with its literal status and is
not retried — a 401 is not a rate limit.

The key never leaves this module
--------------------------------
It rides in one header only. ``source_url`` is the public documentation page,
never the request URL; every reason/error string passes through ``_safe()``,
which strips Bearer credentials, any ``gsk_``-shaped token and any stored vault
value before the string is returned, logged or recorded.

A completion is a draft, not evidence
-------------------------------------
``draft()`` returns text; it does not turn that text into a claim. The live
probe reports which models the key can see (``GET /openai/v1/models``) and emits
no signal, so the ingest bridge writes zero claims from this source. That is
deliberate: an LLM sentence is not a measurement, and this app's citation rule
is that a claim carries evidence, not prose.
"""

from __future__ import annotations

import json
import logging
import re
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone

from . import secrets_vault

log = logging.getLogger("jarvis.groq_source")

COMPONENT_NAME = "GroqSource"

# ---------------------------------------------------------------------------
# statuses
# ---------------------------------------------------------------------------
OK = "OK"
DEGRADED = "DEGRADED"

STATUS_ORDER = (OK, DEGRADED)

# ---------------------------------------------------------------------------
# the credential
# ---------------------------------------------------------------------------
#: The vault name this adapter asks for. Never a value, only a name.
TOKEN_NAME = "GROQ_API_KEY"

#: The literal reason when the vault has nothing. The brief's exact wording.
MISSING_KEY_REASON = "GROQ_API_KEY not set — no request sent"

# ---------------------------------------------------------------------------
# endpoint + request shape
# ---------------------------------------------------------------------------
ENDPOINT = "https://api.groq.com/openai/v1/chat/completions"

#: The cheapest real call a probe can make: list the models this key can use.
#: It verifies the credential and the endpoint without spending generation tokens.
MODELS_ENDPOINT = "https://api.groq.com/openai/v1/models"

#: The model this adapter drafts with. Recorded on every result so a reader can
#: see which model produced the text.
MODEL = "openai/gpt-oss-120b"

#: Public documentation — the citation, never the request URL (which has a key
#: in its header and no key in its path, but the rule is the same everywhere).
SOURCE_URL = "https://console.groq.com/docs/api-reference"

USER_AGENT = ("jarvis-groq-source/1.0 (local orchestrator; "
              "+https://github.com/local/jarvis)")

#: A hard per-attempt ceiling. A slow model is a DEGRADED result, not a hang.
TIMEOUT_SECONDS = 30.0

#: The probe's ceiling: listing models should be quick or not at all.
PROBE_TIMEOUT_SECONDS = 10.0

#: First try + two retries on 429. Any other status is reported immediately.
MAX_ATTEMPTS = 3

#: Exponential backoff for 429: 2s, then 4s (capped at MAX_BACKOFF_SECONDS).
RETRY_BACKOFF_SECONDS = 2.0
BACKOFF_MULTIPLIER = 2.0
MAX_BACKOFF_SECONDS = 8.0

#: Only a rate limit is retried. A 401/403/400 is a real answer.
RETRYABLE_STATUSES = (429,)

TEMPERATURE = 0.2
MAX_TOKENS = 512
MAX_BODY_BYTES = 400_000

#: A row per visible model on the probe card.
COLUMNS = ("Model", "Owned by", "Context window")
PROBE_ROW_LIMIT = 12

#: ``time.sleep`` behind an alias so a test can prove the backoff happens without
#: actually waiting.
_sleep = time.sleep


def _now_iso() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


# ---------------------------------------------------------------------------
# safety: nothing that leaves here may contain the credential
# ---------------------------------------------------------------------------
#: A Groq key looks like ``gsk_...``. Mask it wherever it could have been echoed.
_KEY_PATTERN = re.compile(r"\bgsk_[A-Za-z0-9_\-]{8,}")
_BEARER_PATTERN = re.compile(r"(?i)(authorization\s*:\s*bearer\s+)\S+")


def _safe(text) -> str:
    """Strip a Bearer credential / ``gsk_`` token / stored secret from a string.

    Every reason, error and log line goes through this. The vault's ``scrub()``
    is the belt; the patterns are the braces for a value the vault does not know
    about (a key passed by an operator through a different layer).
    """
    if text is None:
        return ""
    out = str(text)
    out = _BEARER_PATTERN.sub(r"\1REDACTED", out)
    out = _KEY_PATTERN.sub("gsk_REDACTED", out)
    try:
        out = secrets_vault.scrub(out)
    except Exception:  # a broken vault must never crash a request
        pass
    return out


def _snippet(text: str, limit: int = 220) -> str:
    flat = " ".join(str(text or "").split())
    return flat[:limit] + ("…" if len(flat) > limit else "")


# ---------------------------------------------------------------------------
# HTTP (stdlib only)
# ---------------------------------------------------------------------------
def _headers(token: str) -> dict:
    """The one place the credential is put on the wire. Never logged."""
    return {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
        "Accept": "application/json",
    }


def _http(url: str, *, token: str, method: str = "GET",
          body: bytes | None = None,
          timeout: float | None = None) -> tuple[int, str]:
    """One real request. Returns (status_code, body_text). Raises on network error.

    ``timeout`` is the hard ceiling for this attempt and defaults to
    ``TIMEOUT_SECONDS``. The token is used for the Authorization header and is
    never returned, logged or included in either value.
    """
    req = urllib.request.Request(url, data=body, method=method)
    req.add_header("User-Agent", USER_AGENT)
    for key, value in _headers(token).items():
        req.add_header(key, value)
    ceiling = float(timeout if timeout is not None else TIMEOUT_SECONDS)
    try:
        with urllib.request.urlopen(req, timeout=max(1.0, ceiling)) as resp:
            return resp.status, resp.read(MAX_BODY_BYTES).decode("utf-8", "replace")
    except urllib.error.HTTPError as exc:
        return exc.code, exc.read(20_000).decode("utf-8", "replace")


def classify(code: int, text: str = "") -> str:
    """Map a real HTTP response onto one of the two honest statuses."""
    return OK if code == 200 else DEGRADED


# ---------------------------------------------------------------------------
# parsing
# ---------------------------------------------------------------------------
def _content(message) -> str:
    """The assistant text, whether the API sent a string or content parts."""
    if not isinstance(message, dict):
        return ""
    raw = message.get("content")
    if isinstance(raw, str):
        return raw.strip()
    if isinstance(raw, list):
        parts = []
        for part in raw:
            if isinstance(part, dict) and isinstance(part.get("text"), str):
                parts.append(part["text"])
        return "".join(parts).strip()
    return ""


def parse_completion(payload: dict) -> dict:
    """Turn an OpenAI-compatible chat body into the text it really carries.

    Raises ``ValueError`` when the body is not a completion — a 200 whose body
    is an error object must never be presented as generated text.
    """
    if not isinstance(payload, dict):
        raise ValueError("body is not a JSON object")
    choices = payload.get("choices")
    if not isinstance(choices, list) or not choices:
        raise ValueError("body carries no 'choices' array")
    choice = choices[0]
    if not isinstance(choice, dict):
        raise ValueError("choices[0] is not an object")
    message = choice.get("message")
    text = _content(message)
    if not text:
        raise ValueError("choices[0].message.content is empty")
    usage = payload.get("usage") if isinstance(payload.get("usage"), dict) else {}
    return {
        "text": text,
        "model": str(payload.get("model") or MODEL),
        "finish_reason": str(choice.get("finish_reason") or ""),
        "role": str((message or {}).get("role") or "assistant"),
        "usage": {
            "prompt_tokens": usage.get("prompt_tokens"),
            "completion_tokens": usage.get("completion_tokens"),
            "total_tokens": usage.get("total_tokens"),
        },
    }


# ---------------------------------------------------------------------------
# one shape for every outcome
# ---------------------------------------------------------------------------
def _result(status: str, reason: str, *, http_code=None, text: str = "",
            model: str = MODEL, rows=None, columns=None, usage=None,
            attempts: int = 0, retries: int = 0, elapsed_seconds: float = 0.0,
            error: str = "", payload=None) -> dict:
    """Same shape as the keyless adapters, with zero claims on any failure.

    A non-OK status structurally carries no text, no rows and no signals, so a
    refusal cannot be converted into a claim by a caller that forgets to check.
    """
    ok = status == OK
    return {
        "status": status,
        "reason": _safe(reason),
        "http_code": http_code,
        "text": text if ok else "",
        "rows": list(rows or []) if ok else [],
        "columns": list(columns or COLUMNS),
        "signals": [],
        "usage": dict(usage or {}),
        "source_url": SOURCE_URL,
        "endpoint": ENDPOINT,
        "model": model,
        "attempts": int(attempts),
        "retries": int(retries),
        "elapsed_seconds": round(float(elapsed_seconds), 3),
        "error": _safe(error),
        "payload": dict(payload or {}),
        "generated_at": _now_iso(),
    }


def _degraded(reason: str, **kwargs) -> dict:
    log.info("groq: DEGRADED — %s", _snippet(_safe(reason), 300))
    return _result(DEGRADED, reason, **kwargs)


# ---------------------------------------------------------------------------
# draft
# ---------------------------------------------------------------------------
def build_body(prompt: str, context: str = "", *, model: str = MODEL,
               temperature: float = TEMPERATURE,
               max_tokens: int = MAX_TOKENS) -> bytes:
    """The exact JSON body sent to the chat-completions endpoint."""
    messages = []
    if str(context or "").strip():
        messages.append({"role": "system", "content": str(context).strip()})
    messages.append({"role": "user", "content": str(prompt or "").strip()})
    return json.dumps({
        "model": model,
        "messages": messages,
        "temperature": float(temperature),
        "max_tokens": int(max_tokens),
    }).encode("utf-8")


def draft(prompt: str, context: str = "", *, model: str = MODEL,
          temperature: float = TEMPERATURE, max_tokens: int = MAX_TOKENS,
          timeout: float | None = None) -> dict:
    """Ask Groq for a completion and return the text, or an honest refusal.

    ``prompt`` is the user turn; ``context`` (optional) becomes the system turn.
    Every attempt is bounded by ``TIMEOUT_SECONDS`` (or ``timeout``). A 429 is
    retried with exponential backoff up to ``MAX_ATTEMPTS``; every other outcome
    is final and carries its literal HTTP status.
    """
    started = time.monotonic()
    prompt_text = str(prompt or "").strip()
    if not prompt_text:
        return _degraded("empty prompt — no request sent")

    token = secrets_vault.get(TOKEN_NAME)
    if not token:
        # No credential: send nothing, generate nothing, claim nothing.
        return _degraded(MISSING_KEY_REASON)

    body = build_body(prompt_text, context, model=model,
                      temperature=temperature, max_tokens=max_tokens)
    ceiling = float(timeout if timeout is not None else TIMEOUT_SECONDS)

    attempts = 0
    retries = 0
    last_code = None
    last_text = ""
    while attempts < MAX_ATTEMPTS:
        attempts += 1
        try:
            code, text = _http(ENDPOINT, token=token, method="POST",
                               body=body, timeout=ceiling)
        except Exception as exc:  # timeout, DNS, TLS, connection reset
            reason = f"{type(exc).__name__}: {exc}"
            return _degraded(
                reason, error=reason, model=model,
                attempts=attempts, retries=retries,
                elapsed_seconds=time.monotonic() - started,
            )

        last_code, last_text = code, text
        if code == 200:
            try:
                parsed = parse_completion(json.loads(text))
            except (TypeError, ValueError) as exc:
                reason = f"HTTP 200 but the body did not parse: {exc}"
                return _degraded(
                    reason, error=reason, http_code=code, model=model,
                    attempts=attempts, retries=retries,
                    elapsed_seconds=time.monotonic() - started,
                )
            return _result(
                OK,
                (f"{len(parsed['text'])} characters generated by {parsed['model']} "
                 f"(attempt {attempts})"),
                http_code=code,
                text=parsed["text"],
                model=parsed["model"],
                usage=parsed.get("usage"),
                attempts=attempts,
                retries=retries,
                elapsed_seconds=time.monotonic() - started,
                payload={"finish_reason": parsed.get("finish_reason", ""),
                         "role": parsed.get("role", "assistant")},
            )

        if code in RETRYABLE_STATUSES and attempts < MAX_ATTEMPTS:
            backoff = min(RETRY_BACKOFF_SECONDS * (BACKOFF_MULTIPLIER ** (attempts - 1)),
                          MAX_BACKOFF_SECONDS)
            retries += 1
            log.info("groq: HTTP %s — retrying in %.1fs (attempt %d/%d)",
                     code, backoff, attempts + 1, MAX_ATTEMPTS)
            _sleep(backoff)
            continue

        # Any other status — and an exhausted 429 — is the literal answer.
        reason = f"HTTP {code}: {_snippet(text)}"
        return _degraded(
            reason, error=reason, http_code=code, model=model,
            attempts=attempts, retries=retries,
            elapsed_seconds=time.monotonic() - started,
        )

    # The loop can only fall through if every attempt was a retryable status.
    reason = f"HTTP {last_code}: {_snippet(last_text)}"
    return _degraded(
        reason, error=reason, http_code=last_code, model=model,
        attempts=attempts, retries=retries,
        elapsed_seconds=time.monotonic() - started,
    )


# ---------------------------------------------------------------------------
# probe (health check) — one minimal real call, literal status
# ---------------------------------------------------------------------------
def parse_models(payload: dict) -> list[dict]:
    """The model inventory from ``GET /openai/v1/models`` as plain dicts."""
    if not isinstance(payload, dict):
        raise ValueError("body is not a JSON object")
    data = payload.get("data")
    if not isinstance(data, list):
        raise ValueError("body carries no 'data' array")
    out = []
    for item in data:
        if not isinstance(item, dict):
            continue
        model_id = str(item.get("id") or "").strip()
        if not model_id:
            continue
        context = item.get("context_window")
        out.append({
            "id": model_id,
            "owned_by": str(item.get("owned_by") or "—"),
            "context_window": context if isinstance(context, (int, float)) else None,
        })
    return out


def probe(timeout: float | None = None) -> dict:
    """Health check: ``GET /openai/v1/models`` with the vault credential.

    No key -> DEGRADED with the literal reason and NO request. A real 200 is OK
    with the model rows; any other status is DEGRADED with that literal status
    (``http_code``), never smoothed into a pass.
    """
    started = time.monotonic()
    token = secrets_vault.get(TOKEN_NAME)
    if not token:
        return _degraded(MISSING_KEY_REASON)

    ceiling = float(timeout if timeout is not None else PROBE_TIMEOUT_SECONDS)
    try:
        code, text = _http(MODELS_ENDPOINT, token=token, method="GET",
                           timeout=ceiling)
    except Exception as exc:
        reason = f"{type(exc).__name__}: {exc}"
        return _degraded(reason, error=reason,
                         elapsed_seconds=time.monotonic() - started)

    if code != 200:
        reason = f"HTTP {code}: {_snippet(text)}"
        return _degraded(reason, error=reason, http_code=code,
                         elapsed_seconds=time.monotonic() - started)

    try:
        models = parse_models(json.loads(text))
    except (TypeError, ValueError) as exc:
        reason = f"HTTP 200 but the body did not parse: {exc}"
        return _degraded(reason, error=reason, http_code=code,
                         elapsed_seconds=time.monotonic() - started)

    model_available = any(m["id"] == MODEL for m in models)
    rows = []
    for m in models[:PROBE_ROW_LIMIT]:
        context = m["context_window"]
        rows.append([
            m["id"],
            m["owned_by"],
            f"{int(context):,}" if context else "—",
        ])
    return _result(
        OK,
        (f"HTTP 200 — {len(models)} model(s) visible to this key; "
         f"{MODEL} {'available' if model_available else 'not listed'}"),
        http_code=code,
        rows=rows,
        usage={},
        attempts=1,
        elapsed_seconds=time.monotonic() - started,
        payload={"models": [m["id"] for m in models[:PROBE_ROW_LIMIT]],
                 "model_count": len(models),
                 "model": MODEL,
                 "model_available": bool(model_available)},
    )


def health(timeout: float | None = None) -> dict:
    """Alias for :func:`probe` — the health/probe entry point."""
    return probe(timeout=timeout)


def snapshot() -> dict:
    """The live-data layer's entry point. Same name as the keyless adapters."""
    return probe()
