from __future__ import annotations

import os
from pathlib import Path
from typing import Optional

from dotenv import find_dotenv, load_dotenv

_ENV_BOOTSTRAPPED = False


def load_navexa_env(env_file: Optional[str] = None, *, override: bool = False) -> bool:
    global _ENV_BOOTSTRAPPED

    if _ENV_BOOTSTRAPPED and env_file is None:
        return False

    loaded_any = False

    explicit = env_file or os.getenv("NAVEXA_ENV_FILE")
    if explicit:
        explicit_path = Path(explicit).expanduser()
        if explicit_path.exists():
            loaded_any = bool(load_dotenv(explicit_path, override=override)) or loaded_any

    found = find_dotenv(usecwd=True)
    if found:
        loaded_any = bool(load_dotenv(found, override=override)) or loaded_any

    # Backward compatibility for local repo execution.
    repo_env = Path(__file__).resolve().parents[2] / ".env"
    if repo_env.exists():
        loaded_any = bool(load_dotenv(repo_env, override=override)) or loaded_any

    _ENV_BOOTSTRAPPED = True
    return loaded_any

