"""THE SECRETS VAULT — a local-first store for the API keys this app needs.

Where it lives
--------------
One JSON file, outside the project tree:

    $JARVIS_SECRETS_FILE          (if set, and NOT inside the repo)
    ~/.jarvis/secrets.json        (default)

The parent directory is created with mode ``0700`` and the file is written with
mode ``0600``. There is no code path that writes a secret into the repo, into the
audit ledger, into a claim, into a ``source_url`` or into an HTTP response.

Resolution order (``get``)
--------------------------
    1. an environment variable  (MAPBOX_TOKEN / MAPBOX_API_KEY / ...)
    2. the secrets file          (~/.jarvis/secrets.json)
    3. None

The environment wins so an operator can override a stored credential for a single
process without editing the file. ``source(name)`` reports which layer answered:
``"env"``, ``"file"`` or ``None``.

What is never allowed to leave
------------------------------
``get()`` is the only function that returns a raw value, it does not log, and the
value it returns is used for exactly one thing: putting the credential on the
wire. Everything that *can* be seen by a human or by a response body goes through
``redact()`` (``"abcd…"``), ``list_names()`` (names only), ``status()``
(``PRESENT`` / ``MISSING``) or ``scrub()`` (belt-and-braces masking of any value
that ends up inside an error string).

``set()`` writes exactly one audit row: the key NAME and whether it is present.
The value is never written to the ledger, never logged, never returned.
"""

from __future__ import annotations

import json
import logging
import os
import re
import tempfile
import threading
import urllib.parse
from datetime import datetime, timezone

from . import audit

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

COMPONENT_NAME = "SecretsVault"

#: Environment variable that points the vault at a different file (tests, ops).
PATH_ENV = "JARVIS_SECRETS_FILE"

#: Accepted alias for the same override (the documented spelling in the brief).
PATH_ENV_ALIASES = (PATH_ENV, "JARVIS_SECRETS_PATH")

#: Default location. Deliberately outside the project tree.
DEFAULT_PATH = "~/.jarvis/secrets.json"

#: The project tree. Nothing here is ever written below this path.
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

#: The names the adapters ask for. ``status()`` reports exactly these.
KNOWN_KEYS = (
    "MAPBOX_TOKEN",
    "RENTCAST_API_KEY",
    "INTERFAZE_API_KEY",
    "PARALLEL_API_KEY",
    "GROQ_API_KEY",
    "TAVILY_API_KEY",
)

#: Accepted spellings for a known key. The canonical name is checked first, so a
#: deployment that already exports MAPBOX_ACCESS_TOKEN keeps working.
ALIASES = {
    "MAPBOX_TOKEN": ("MAPBOX_TOKEN", "MAPBOX_API_KEY", "MAPBOX_ACCESS_TOKEN"),
}

#: Spellings the vault FILE may use for a known name. The canonical name is read
#: first; these are only consulted when it is absent, so nothing is duplicated in
#: the file. ``tavily`` is stored lowercase, exactly as the brief names it.
VAULT_ALIASES = {
    "TAVILY_API_KEY": ("tavily",),
}

#: A key name: no spaces, no path tricks, bounded length.
NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.\-]{0,63}$")

PRESENT = "PRESENT"
MISSING = "MISSING"

#: A value at least this long gets its first four characters shown by redact().
REDACT_MIN_LEN = 8

LOCK = threading.RLock()


class SecretsError(ValueError):
    """A bad name or an empty value. Maps to HTTP 400."""


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


# ---------------------------------------------------------------------------
# where the file lives
# ---------------------------------------------------------------------------
def _inside_repo(path: str) -> bool:
    target = os.path.abspath(path)
    try:
        return os.path.commonpath([target, REPO_ROOT]) == REPO_ROOT
    except ValueError:  # different drives on Windows
        return False


def _default_path() -> str:
    return os.path.abspath(os.path.expanduser(DEFAULT_PATH))


def secrets_path() -> str:
    """The absolute path of the vault file. Never inside the project tree."""
    for env_name in PATH_ENV_ALIASES:
        override = os.environ.get(env_name, "").strip()
        if not override:
            continue
        target = os.path.abspath(os.path.expanduser(override))
        if _inside_repo(target):
            # Refuse, do not raise: a misconfigured env var must not take the app
            # down, and it must never cause a secret to be written into the repo.
            log.warning("%s points inside the project tree; using the default vault instead",
                        env_name)
            return _default_path()
        return target
    return _default_path()


def secrets_dir() -> str:
    return os.path.dirname(secrets_path()) or "."


def path_display() -> str:
    """Where the vault lives, for the UI. A path is not a secret."""
    return secrets_path()


# ---------------------------------------------------------------------------
# masking
# ---------------------------------------------------------------------------
def redact(value) -> str:
    """``"pk.eyJabc123"`` -> ``"pk.e…"``. Safe to print, log or render.

    A short value (``< 8`` characters) is masked completely: showing four of six
    characters would be most of the secret.
    """
    if value is None:
        return ""
    text = str(value)
    if not text:
        return ""
    if len(text) < REDACT_MIN_LEN:
        return "…"
    return f"{text[:4]}…"


def _variants(value: str) -> set[str]:
    """The shapes a value takes once it has been put into a URL or a header."""
    out = {value}
    for quoted in (urllib.parse.quote(value, safe=""), urllib.parse.quote(value)):
        if quoted:
            out.add(quoted)
    return out


def scrub(text) -> str:
    """Replace every stored secret that appears in ``text`` with its masked form.

    Used on probe evidence before it is recorded anywhere, so a credential that
    an exception message picked up out of a URL still cannot reach the ledger.
    """
    if text is None:
        return ""
    out = str(text)
    if not out:
        return out
    try:
        stored = _load()
    except Exception:  # a broken vault must never crash a probe
        return out
    for value in stored.values():
        if not value or len(value) < 4:
            continue
        for variant in _variants(value):
            if variant and variant in out:
                out = out.replace(variant, redact(value))
    return out


# ---------------------------------------------------------------------------
# file I/O
# ---------------------------------------------------------------------------
def _read_unlocked() -> dict[str, str]:
    path = secrets_path()
    try:
        with open(path, "r", encoding="utf-8") as fh:
            payload = json.load(fh)
    except FileNotFoundError:
        return {}
    except (OSError, ValueError) as exc:
        # Never echo the contents: the exception type is enough.
        log.warning("secrets vault at %s is unreadable (%s); treating it as empty",
                    path, type(exc).__name__)
        return {}
    if not isinstance(payload, dict):
        return {}
    inner = payload.get("keys")
    source = inner if isinstance(inner, dict) else payload
    return {
        str(k): str(v)
        for k, v in source.items()
        if isinstance(v, str) and v.strip() and NAME_RE.match(str(k))
    }


def _load() -> dict[str, str]:
    with LOCK:
        return _read_unlocked()


def _write_unlocked(keys: dict[str, str]) -> None:
    path = secrets_path()
    directory = os.path.dirname(path) or "."
    os.makedirs(directory, mode=0o700, exist_ok=True)
    try:
        os.chmod(directory, 0o700)
    except OSError:  # pragma: no cover - filesystems without chmod
        pass

    fd, tmp = tempfile.mkstemp(prefix=".secrets-", suffix=".tmp", dir=directory)
    try:
        try:
            os.fchmod(fd, 0o600)
        except (AttributeError, OSError):  # pragma: no cover
            pass
        with os.fdopen(fd, "w", encoding="utf-8") as fh:
            json.dump(
                {
                    "version": 1,
                    "updated_at": _now_iso(),
                    "note": "JARVIS local secrets vault. Mode 0600. Never commit this file.",
                    "keys": keys,
                },
                fh,
                indent=2,
                ensure_ascii=False,
            )
            fh.write("\n")
            fh.flush()
            os.fsync(fh.fileno())
        os.replace(tmp, path)
    except Exception:
        try:
            os.unlink(tmp)
        except OSError:
            pass
        raise
    try:
        os.chmod(path, 0o600)
    except OSError:  # pragma: no cover
        pass


def _audit_change(name: str, present: bool, action: str) -> None:
    """One ledger row per change: the NAME and whether it is present. No value."""
    try:
        audit.record(
            actor=COMPONENT_NAME,
            action=action,
            subject_type="secret",
            subject_id=name,
            payload={"name": name, "present": bool(present), "layer": "file"},
        )
    except Exception as exc:  # pragma: no cover - never block a write on the ledger
        log.warning("audit write failed for %s (%s): %s", action, name, type(exc).__name__)


# ---------------------------------------------------------------------------
# the API
# ---------------------------------------------------------------------------
def _check_name(name) -> str:
    clean = str(name or "").strip()
    if not clean:
        raise SecretsError("a key name is required")
    if not NAME_RE.match(clean):
        raise SecretsError(
            "a key name must be 1-64 characters of letters, digits, '.', '_' or '-'"
        )
    return clean


def _env_names(name: str) -> tuple[str, ...]:
    return ALIASES.get(name, (name,))


def _file_names(name: str) -> tuple[str, ...]:
    """The vault-file spellings to try, canonical name first."""
    return (name, *VAULT_ALIASES.get(name, ()))


def _stored(stored: dict[str, str], name: str):
    """The value stored under any accepted spelling, or ``None``."""
    for candidate in _file_names(name):
        value = stored.get(candidate)
        if value is not None and value.strip():
            return value.strip()
    return None


def get(name: str):
    """The raw value, or ``None``. Never logs, never prints, never audits.

    Resolution: environment -> secrets file -> ``None``.
    """
    clean = str(name or "").strip()
    if not clean:
        return None
    for env_name in _env_names(clean):
        raw = os.environ.get(env_name, "")
        if raw and raw.strip():
            return raw.strip()
    return _stored(_load(), clean)


def has(name: str) -> bool:
    return get(name) is not None


def source(name: str):
    """Which layer supplied the value: ``"env"``, ``"file"`` or ``None``."""
    clean = str(name or "").strip()
    if not clean:
        return None
    for env_name in _env_names(clean):
        raw = os.environ.get(env_name, "")
        if raw and raw.strip():
            return "env"
    if _stored(_load(), clean):
        return "file"
    return None


def set(name, value) -> None:  # noqa: A001 - the documented API name
    """Store/replace one credential. The value goes nowhere but the file."""
    clean = _check_name(name)
    raw = "" if value is None else str(value).strip()
    if not raw:
        raise SecretsError("a key value is required")
    if len(raw) > 4096:
        raise SecretsError("a key value must be 4096 characters or fewer")
    with LOCK:
        keys = _read_unlocked()
        keys[clean] = raw
        _write_unlocked(keys)
    log.info("secrets: stored %s (present=True, %d chars)", clean, len(raw))
    _audit_change(clean, True, "secrets.set")


def delete(name) -> bool:
    """Remove a stored credential. Returns whether anything was there."""
    clean = _check_name(name)
    with LOCK:
        keys = _read_unlocked()
        existed = clean in keys
        if existed:
            del keys[clean]
            _write_unlocked(keys)
    if existed:
        log.info("secrets: deleted %s (present=False)", clean)
        _audit_change(clean, False, "secrets.delete")
    return existed


def list_names() -> list[str]:
    """Every known name plus every stored name. NAMES ONLY — never values."""
    try:
        stored = _load()
    except Exception:  # pragma: no cover - a broken vault lists the known names
        stored = {}
    names = list(KNOWN_KEYS)
    # A stored alias spelling (``tavily``) is the same credential as its canonical
    # name, so it is not listed twice.
    aliases = {a for spellings in VAULT_ALIASES.values() for a in spellings}
    names += sorted(n for n in stored if n not in KNOWN_KEYS and n not in aliases)
    return names


def status() -> dict:
    """``{name: "PRESENT"|"MISSING"}`` for the known keys. Values never included."""
    return {name: (PRESENT if has(name) else MISSING) for name in KNOWN_KEYS}


def summary() -> dict:
    """A shape the UI and the JSON API can render without touching a value."""
    st = status()
    return {
        "path": path_display(),
        "keys": st,
        "present": sum(1 for v in st.values() if v == PRESENT),
        "missing": sum(1 for v in st.values() if v == MISSING),
        "names": list_names(),
    }
