"""Locate the runtime settings file (``.env``) that backs the Settings UI. WHY THIS EXISTS --------------- The Settings page persists browser/HITL knobs by rewriting the ``.env`` file that ``pydantic-settings`` loads at startup. That file has to be the SAME file on both sides — the writer in ``settings_store.py`` and the reader in ``config.py`` — or a saved value silently disappears on the next boot. Two environments need different paths: * **Local / compose** — the process runs from the checkout, so ``.env`` in the working directory is right and survives a restart. * **Hugging Face Space** — the process runs from ``/app``, which is owned by root and NOT writable by the unprivileged ``appuser`` the image drops to. Writing ``/app/.env`` raised ``PermissionError``, which surfaced as HTTP 500 on every save (the live mutation had already been applied, so the operator was told "failed" while the value was actually live). The Space mounts persistent storage at ``/data``, which is writable and survives a rebuild. ``DRACULL_ENV_FILE`` selects the file. It is read once, at import time, and both modules resolve it through this helper so they can never disagree. Resolution order: 1. ``DRACULL_ENV_FILE`` — absolute path, used verbatim. 2. ``.env`` in the current working directory (the local default). 3. ``/data/.env`` when the working directory is not writable — the hosted fallback, so a save never fails for a reason the operator cannot fix. """ from __future__ import annotations import os from pathlib import Path #: Environment variable that overrides the settings-file location. ENV_FILE_ENV_VAR = "DRACULL_ENV_FILE" #: Hosted fallback: the persistent storage mount on a Hugging Face Space. HOSTED_FALLBACK = Path("/data/.env") def _writable_dir(directory: Path) -> bool: """True when a file can be created in ``directory``. Checked with a real touch-and-delete rather than an access() probe: the container runs as an unprivileged user, so the mode bits alone do not decide the outcome. """ probe = directory / ".dracull-write-probe" try: probe.touch() except OSError: return False try: probe.unlink() except OSError: pass return True def resolve_env_file() -> Path: """The settings file the backend reads at startup and writes on save.""" configured = os.environ.get(ENV_FILE_ENV_VAR, "").strip() if configured: return Path(configured).expanduser() cwd_env = Path.cwd() / ".env" if _writable_dir(cwd_env.parent): return cwd_env return HOSTED_FALLBACK def ensure_parent(path: Path) -> None: """Create the parent directory of ``path`` when it is missing.""" parent = path.parent if not parent.exists(): parent.mkdir(parents=True, exist_ok=True)