"""Consistent, secret-safe unattended failure reporting."""

from __future__ import annotations

import traceback
from datetime import datetime, timezone

from notify import ROOT, env_path


def redact_env_values(text: str) -> str:
    # Must resolve the same way notify does. On the box the secrets are not in
    # ROOT/.env but in the systemd credential path — reading the wrong file here
    # would mean tracebacks go out UNREDACTED, which is the one thing this module
    # exists to prevent.
    source = env_path()
    values: list[str] = []
    if source.exists():
        for raw_line in source.read_text(encoding="utf-8").splitlines():
            line = raw_line.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            _, value = line.split("=", 1)
            value = value.strip()
            if value:
                values.append(value)
                compact = value.replace(" ", "")
                if compact and compact != value:
                    values.append(compact)
    redacted = text
    for value in sorted(set(values), key=len, reverse=True):
        redacted = redacted.replace(value, "[REDACTED]")
    return redacted


def record_failure(context: str, error: BaseException) -> str:
    summary = redact_env_values(f"{type(error).__name__}: {error}")
    full_traceback = redact_env_values(
        "".join(traceback.format_exception(type(error), error, error.__traceback__))
    )
    timestamp = datetime.now(timezone.utc).isoformat()
    log_path = ROOT / "logs" / "error.log"
    log_path.parent.mkdir(parents=True, exist_ok=True)
    with log_path.open("a", encoding="utf-8", newline="\n") as handle:
        handle.write(f"[{timestamp}] {context}: {summary}\n")
        handle.write(full_traceback.rstrip() + "\n\n")
    return summary