from __future__ import annotations

from pathlib import Path
import os


def load_env_file(path: str | os.PathLike = "env", *, override: bool = False) -> dict[str, str]:
    """
    간단한 .env 로더(외부 의존성 없이 사용).

    - 형식: KEY=VALUE (공백 허용)
    - 주석: 라인 시작이 # 이면 무시
    - override=False: 이미 os.environ에 있는 키는 덮어쓰지 않음
    - 반환: 로드된 key->value
    """
    p = Path(path)
    if not p.is_absolute():
        # 호출 위치와 무관하게 "이 파일이 있는 폴더" 기준으로 찾고,
        # 없으면 현재 작업 디렉터리도 한번 더 본다.
        here = Path(__file__).resolve().parent
        cand = here / p
        if cand.exists():
            p = cand
        else:
            p = Path.cwd() / p

    if not p.exists():
        return {}

    loaded: dict[str, str] = {}
    try:
        text = p.read_text(encoding="utf-8", errors="ignore")
    except Exception:
        return {}

    for raw_line in text.splitlines():
        line = str(raw_line).strip()
        if not line or line.startswith("#"):
            continue
        if "=" not in line:
            continue
        k, v = line.split("=", 1)
        k = k.strip()
        v = v.strip()
        if not k:
            continue
        if (not override) and (k in os.environ):
            continue
        os.environ[k] = v
        loaded[k] = v

    return loaded

