"""Load a local, git-ignored .env for PyCharm/runserver without shell execution.

Environment variables supplied by Docker, CI, or the host always win. The loader
never loads .env.production implicitly, and can be disabled with FTG_DISABLE_DOTENV=1.
"""
from __future__ import annotations

import os
from pathlib import Path
import re

_KEY = re.compile(r"^[A-Za-z_][A-Za-z_0-9]*$")


def load_local_env(path: Path | None = None) -> int:
    if os.environ.get('FTG_DISABLE_DOTENV', '').lower() in ('1', 'true', 'yes'):
        return 0
    file_path = path if path is not None else Path(__file__).resolve().parent.parent / '.env'
    if not file_path.is_file():
        return 0
    loaded = 0
    for raw in file_path.read_text(encoding='utf-8-sig').splitlines():
        line = raw.strip()
        if not line or line.startswith('#'):
            continue
        if line.startswith('export '):
            line = line[7:].strip()
        if '=' not in line:
            continue
        name, value = line.split('=', 1)
        name = name.strip()
        if not _KEY.fullmatch(name):
            continue
        value = value.strip()
        if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
            value = value[1:-1]
        if name not in os.environ:
            os.environ[name] = value
            loaded += 1
    return loaded
