"""THE TAVILY ADAPTER — real web search, gated by the vault, cited by URL.

Why this file exists
--------------------
Tavily is the research step of the loop: the one adapter that answers "what is
being said about this market right now" instead of "how many of them are
there". It returns real pages with real URLs, so a signal it feeds can always be
traced back to the page it came from.

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

    HTTP 200 + parseable JSON   -> "OK"        real search results
    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"  "TAVILY_API_KEY not set — no request sent"

On every non-OK status the result carries ``rows == []`` and ``signals == []``,
so a refusal can never be turned into a claim by a caller that forgets to check.

No credential, no request
-------------------------
``_token()`` asks the vault — environment first, then the stored file — and its
answer decides whether a request happens at all. The vault stores this one under
the brief's spelling ``tavily``; ``TAVILY_API_KEY`` is the canonical name and is
resolved first, so an operator who exports it never has to touch the file.

Transport
---------
``POST https://api.tavily.com/search`` with ``Authorization: Bearer <key>`` and
a JSON body of ``{query, max_results, search_depth}``. 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 ``tvly_``-shaped token and any stored vault
value before the string is returned, logged or recorded.

A search hit is a pointer, not a measurement
--------------------------------------------
``search()`` returns rows with the page's title, URL, relevance score and a
snippet. That is why this adapter emits no derived signal and therefore zero
claims through the ingest bridge: a snippet tells you where to look, not how
many businesses exist or what the price is. ``live_data`` still shows the real
result count and the real URLs, which is the evidence a reader can check.
"""

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.tavily_source")

COMPONENT_NAME = "TavilySource"

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

STATUS_ORDER = (OK, DEGRADED)

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

#: The spelling the vault file uses for the same credential (lowercase, as the
#: brief names it). Resolved only when the canonical name is absent.
VAULT_ALIASES = ("tavily",)

#: The literal reason when the vault has nothing.
MISSING_KEY_REASON = "TAVILY_API_KEY not set — no request sent"

# ---------------------------------------------------------------------------
# endpoint + request shape
# ---------------------------------------------------------------------------
ENDPOINT = "https://api.tavily.com/search"

#: Public documentation — the citation, never the request URL. The key rides in
#: a header, but the rule is the same everywhere: cite the docs, not the call.
SOURCE_URL = "https://docs.tavily.com/documentation/api-reference/endpoint/search"

#: The query the probe and the default search run. A real local market question
#: this app actually cares about, so a LIVE card shows something usable.
DEFAULT_QUERY = "HVAC contractor demand Rochester NY winter"

#: How many results a search returns (Tavily caps this at 20).
MAX_RESULTS = 5

#: ``basic`` is the cheap real search: one round trip, no advanced crawling.
SEARCH_DEPTH = "basic"

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

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

#: The probe's ceiling: a health check should be quick or not at all.
PROBE_TIMEOUT_SECONDS = 15.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,)

MAX_BODY_BYTES = 400_000

#: One row per result on the card.
COLUMNS = ("Title", "URL", "Score", "Snippet")

#: How much of each result's content becomes the snippet cell.
SNIPPET_CHARS = 160

#: ``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")


# ---------------------------------------------------------------------------
# the credential
# ---------------------------------------------------------------------------
def _token():
    """The raw credential, or ``None``. Environment first, then the vault file.

    ``TAVILY_API_KEY`` is asked for by name; the vault's lowercase ``tavily``
    spelling is the fallback the brief asks for. The value is returned to the
    caller and put on one header — never logged, never recorded.
    """
    value = secrets_vault.get(TOKEN_NAME)
    if value:
        return value
    for alias in VAULT_ALIASES:
        value = secrets_vault.get(alias)
        if value:
            return value
    return None


def credential_source():
    """``"env"``, ``"file"`` or ``None`` — which layer supplied the key."""
    layer = secrets_vault.source(TOKEN_NAME)
    if layer:
        return layer
    for alias in VAULT_ALIASES:
        if secrets_vault.source(alias):
            return "file"
    return None


# ---------------------------------------------------------------------------
# safety: nothing that leaves here may contain the credential
# ---------------------------------------------------------------------------
#: A Tavily key looks like ``tvly-...``. Mask it wherever it could be echoed.
_KEY_PATTERN = re.compile(r"\btvly-[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 / ``tvly-`` 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("tvly-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 = "POST",
          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 parse_results(payload: dict) -> dict:
    """Turn a Tavily search body into the results it really carries.

    Raises ``ValueError`` when the body is not a search response — a 200 whose
    body is an error object must never be presented as results.
    """
    if not isinstance(payload, dict):
        raise ValueError("body is not a JSON object")
    raw = payload.get("results")
    if not isinstance(raw, list):
        raise ValueError("body carries no 'results' array")

    results = []
    for item in raw:
        if not isinstance(item, dict):
            continue
        url = str(item.get("url") or "").strip()
        title = str(item.get("title") or "").strip()
        if not url and not title:
            # A row with neither a title nor a URL cites nothing.
            continue
        score = item.get("score")
        results.append({
            "title": title or url,
            "url": url,
            "score": float(score) if isinstance(score, (int, float)) else None,
            "content": " ".join(str(item.get("content") or "").split()),
        })

    response_time = payload.get("response_time")
    return {
        "query": str(payload.get("query") or ""),
        "results": results,
        "count": len(results),
        "answer": str(payload.get("answer") or "").strip(),
        "response_time": (float(response_time)
                          if isinstance(response_time, (int, float)) else None),
        "request_id": str(payload.get("request_id") or ""),
    }


def _rows(parsed: dict) -> list[list[str]]:
    """The parsed results as the card's four display columns."""
    out = []
    for item in parsed["results"]:
        out.append([
            item["title"],
            item["url"] or "—",
            f"{item['score']:.2f}" if item.get("score") is not None else "—",
            _snippet(item.get("content", ""), SNIPPET_CHARS) or "—",
        ])
    return out


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

    A non-OK status structurally carries 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,
        "rows": list(rows or []) if ok else [],
        "columns": list(columns or COLUMNS),
        "signals": [],
        "result_count": len((parsed or {}).get("results") or []) if ok else 0,
        "source_url": SOURCE_URL,
        "endpoint": ENDPOINT,
        "query": str(query or (parsed or {}).get("query") or ""),
        "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("tavily: DEGRADED — %s", _snippet(_safe(reason), 300))
    return _result(DEGRADED, reason, **kwargs)


# ---------------------------------------------------------------------------
# search
# ---------------------------------------------------------------------------
def build_body(query: str, *, max_results: int = MAX_RESULTS,
               search_depth: str = SEARCH_DEPTH,
               include_answer: bool = False) -> bytes:
    """The exact JSON body sent to the search endpoint.

    The credential is deliberately NOT in this body: it rides the Authorization
    header, so a body captured anywhere (a log, an error echo) carries no secret.
    """
    return json.dumps({
        "query": str(query or "").strip(),
        "max_results": max(1, min(int(max_results), 20)),
        "search_depth": str(search_depth),
        "include_answer": bool(include_answer),
        "include_raw_content": False,
        "include_images": False,
    }).encode("utf-8")


def search(query: str = DEFAULT_QUERY, *, max_results: int = MAX_RESULTS,
           search_depth: str = SEARCH_DEPTH, timeout: float | None = None) -> dict:
    """Run a real Tavily search and return the results, or an honest refusal.

    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()
    query_text = str(query or "").strip()
    if not query_text:
        return _degraded("empty query — no request sent")

    token = _token()
    if not token:
        # No credential: send nothing, return nothing, claim nothing.
        return _degraded(MISSING_KEY_REASON, query=query_text)

    body = build_body(query_text, max_results=max_results,
                      search_depth=search_depth)
    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, query=query_text,
                attempts=attempts, retries=retries,
                elapsed_seconds=time.monotonic() - started,
            )

        last_code, last_text = code, text
        if code == 200:
            try:
                parsed = parse_results(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, query=query_text,
                    attempts=attempts, retries=retries,
                    elapsed_seconds=time.monotonic() - started,
                )
            rt = parsed.get("response_time")
            return _result(
                OK,
                (f"HTTP 200 — {parsed['count']} result(s) for {query_text!r}"
                 + (f" in {rt:.2f}s" if rt else "")
                 + (f" (attempt {attempts})" if attempts > 1 else "")),
                http_code=code,
                rows=_rows(parsed),
                parsed=parsed,
                query=parsed.get("query") or query_text,
                attempts=attempts,
                retries=retries,
                elapsed_seconds=time.monotonic() - started,
                payload={
                    "query": parsed.get("query") or query_text,
                    "result_count": parsed["count"],
                    "response_time": rt,
                    "request_id": parsed.get("request_id", ""),
                    "answer": parsed.get("answer", ""),
                    "urls": [r["url"] for r in parsed["results"]],
                },
            )

        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("tavily: 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, query=query_text,
            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, query=query_text,
        attempts=attempts, retries=retries,
        elapsed_seconds=time.monotonic() - started,
    )


# ---------------------------------------------------------------------------
# probe (health check) — one real authenticated search, literal status
# ---------------------------------------------------------------------------
def probe(timeout: float | None = None) -> dict:
    """Health check: one real authenticated ``POST /search`` with the vault key.

    No key -> DEGRADED with the literal reason and NO request. A real 200 is OK
    carrying the result rows, their count and the URLs; any other status is
    DEGRADED with that literal status (``http_code``), never smoothed into a pass.
    """
    return search(DEFAULT_QUERY, max_results=MAX_RESULTS,
                  timeout=PROBE_TIMEOUT_SECONDS if timeout is None else timeout)


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 other adapters."""
    return probe()
