"""Stable .env loading for MCube and agent_runtime processes.

Historically, modules used ``load_dotenv(".env.local")``, which only works when the
process cwd is ``agent_runtime/``. This module loads from fixed paths:

1. ``backend/.env`` — same file Django uses (shared secrets / MCube vars)
2. ``backend/agent_runtime/.env.local`` — optional overrides (wins on duplicate keys)

Set ``AGENT_RUNTIME_ENV_FILE`` to an absolute path to load only that file
(``override=True``), for ad-hoc testing.
"""

from __future__ import annotations

import os
from pathlib import Path

from dotenv import load_dotenv

_AGENT_RUNTIME_ROOT = Path(__file__).resolve().parent.parent.parent
_BACKEND_ROOT = _AGENT_RUNTIME_ROOT.parent


def load_agent_runtime_dotenv() -> None:
    explicit = os.getenv("AGENT_RUNTIME_ENV_FILE", "").strip()
    if explicit:
        load_dotenv(Path(explicit), override=True)
        return
    load_dotenv(_BACKEND_ROOT / ".env", override=False)
    load_dotenv(_AGENT_RUNTIME_ROOT / ".env.local", override=True)
