"""Environment access tracking for env_fingerprint."""

from __future__ import annotations

import hashlib
import os
from typing import Dict

_env_access: Dict[str, str] = {}
_original_getenv = os.getenv
_original_getitem = os.environ.__getitem__
_original_environ_get = os.environ.get
_original_environ_pop = os.environ.pop
_original_environ_setdefault = os.environ.setdefault


def _hash_value(value: str) -> str:
    return hashlib.sha256(value.encode("utf-8")).hexdigest()


def _record(name: str, value: object | None) -> None:
    if value is None:
        return
    if name not in _env_access:
        _env_access[name] = _hash_value(str(value))


def patched_getenv(key: str, default: object | None = None) -> object | None:
    value = _original_getenv(key, default)
    _record(key, value)
    return value


def patched_getitem(key: str) -> str:
    value = _original_getitem(key)
    _record(key, value)
    return value


def patched_environ_get(key: str, default: object | None = None) -> object | None:
    value = _original_environ_get(key, default)
    _record(key, value)
    return value


def patched_environ_pop(key: str, *args) -> str:
    value = _original_environ_pop(key, *args)
    _record(key, value)
    return value


def patched_environ_setdefault(key: str, value: str = "") -> str:
    result = _original_environ_setdefault(key, value)
    _record(key, result)
    return result


def install() -> None:
    os.getenv = patched_getenv  # type: ignore[assignment]
    os.environ.__getitem__ = patched_getitem  # type: ignore[assignment]
    os.environ.get = patched_environ_get  # type: ignore[assignment]
    os.environ.pop = patched_environ_pop  # type: ignore[assignment]
    os.environ.setdefault = patched_environ_setdefault  # type: ignore[assignment]


def env_fingerprint() -> Dict[str, str]:
    return dict(_env_access)
