"""Bounded native dependency errors; inspect only this child's private output and environment."""
import base64
import os
import re
from urllib.parse import unquote, urlsplit

SENSITIVE = re.compile(r"SECRET|TOKEN|PASSWORD|PROXY|PRIVATE_KEY|SERVICE_ACCOUNT|CREDENTIAL", re.I)


def values(environment: dict[str, str]) -> set[str]:
    found = set()
    for key, value in environment.items():
        if not SENSITIVE.search(key) or len(value) < 4:
            continue
        found.add(value)
        try:
            proxy = urlsplit(value)
            if proxy.username is not None:
                user, password = unquote(proxy.username), unquote(proxy.password or "")
                found.update((user, password, base64.b64encode(f"{user}:{password}".encode()).decode()))
        except ValueError:
            pass
    return {value for value in found if value}


def excerpt(text: str) -> str:
    lines = text.splitlines()
    tail = "\n".join(lines[-30:])[-4000:]
    start = next((index for index in range(len(lines) - 1, -1, -1)
                  if lines[index].strip() == "### Error"), None)
    if start is None:
        return tail
    primary = "\n".join(lines[start:start + 6])[:1200]
    if primary in tail:
        return tail
    tail = "\n".join(lines[-(29 - len(primary.splitlines())):])[-(3995 - len(primary)):]
    return primary + "\n...\n" + tail


#: A long run that is a lowercase snake_case NAME rather than an opaque value.
#: Thirteen of this helper's own error codes are 32 characters or more —
#: `native_podfile_lock_commit_required` is 35, `native_google_transport_helper_required`
#: is 39 — so the catch-all below erased the one token the classifier reads back
#: out of this text: task 1185's iOS failure published `"code": "[long value
#: redacted]"` with an empty `signals` list, and every pods failure in the fleet
#: was diagnosed blind (2026-09-09). Requiring an underscore keeps hex digests and
#: base32/base64 material opaque, and every environment value has already been
#: replaced verbatim above.
_NAME_RUN = re.compile(r"[a-z]+(?:_[a-z0-9]+)+")


def _opaque_run(match: "re.Match[str]") -> str:
    run = match.group(0)
    return run if _NAME_RUN.fullmatch(run) else "[long value redacted]"


def diagnostic(log, environment: dict[str, str] | None = None) -> str:
    log.flush()
    log.seek(0, os.SEEK_END)
    start = max(0, log.tell() - 16384)
    log.seek(start)
    body = log.read()
    if start:
        body = body.partition(b"\n")[2]
    text = body.decode("utf-8", errors="replace")
    for value in sorted(values(environment if environment is not None else dict(os.environ)), key=len, reverse=True):
        text = text.replace(value, "[redacted]")
    text = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", text)
    text = re.sub(r"-----BEGIN [^-]*PRIVATE KEY-----.*?(?:-----END [^-]*PRIVATE KEY-----|$)",
                  "[private key redacted]", text, flags=re.S)
    text = re.sub(r"(?im)^\s*[A-Za-z0-9+/=]{48,}\s*$", "[encoded value redacted]", text)
    text = re.sub(r"(?i)\b(?:proxy-authorization|authorization)\s*:[^\r\n]*", "authorization: [redacted]", text)
    text = re.sub(r'(?i)("(?:private_key|client_secret|password|access_token|refresh_token)"\s*:\s*)"(?:\\.|[^"\\])*"',
                  r'\1"[redacted]"', text)
    text = re.sub(r"\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", "[token redacted]", text)
    text = re.sub(r"https?://[^\s\"'<>]+", "[URL redacted]", text)
    text = re.sub(r"[A-Za-z0-9_+/=-]{32,}", _opaque_run, text)
    return excerpt(text)


def refuse(code: str, log, exception):
    error = exception(code)
    error.diagnostic = diagnostic(log)
    raise error
