"""Config package initializer，保持对旧 `from config import ...` 的兼容。"""

import os
from pathlib import Path


def _load_dotenv():
    """在未显式导入 python-dotenv 的情况下，尽量从仓库根目录加载 .env。"""
    env_path = Path(__file__).resolve().parents[1] / ".env"
    if not env_path.exists():
        return
    # 仅保护启动前已有的环境变量；.env 内重复键以后者为准
    pre_existing_keys = set(os.environ.keys())
    try:
        for raw_line in env_path.read_text(encoding="utf-8").splitlines():
            line = raw_line.strip()
            if not line or line.startswith("#"):
                continue
            if "=" not in line:
                continue
            key, value = line.split("=", 1)
            key = key.strip()
            value = value.strip().strip('"').strip("'")
            if not key:
                continue
            # 若在进程启动前已存在，则尊重外部环境；否则允许 .env 内后续行覆盖前面行
            if key in pre_existing_keys:
                continue
            os.environ[key] = value
    except Exception:
        # 加载失败时静默继续，保持兼容
        pass


_load_dotenv()

from . import api as _api
from . import paths as _paths
from . import limits as _limits
from . import terminal as _terminal
from . import conversation as _conversation
from . import security as _security
from . import ui as _ui
from . import memory as _memory
from . import ocr as _ocr
from . import todo as _todo
from . import auth as _auth
from . import uploads as _uploads
from . import sub_agent as _sub_agent
from . import custom_tools as _custom_tools
from . import mcp as _mcp

from .api import *
from .paths import *
from .limits import *
from .terminal import *
from .conversation import *
from .security import *
from .ui import *
from .memory import *
from .ocr import *
from .todo import *
from .auth import *
from .uploads import *
from .sub_agent import *
from .custom_tools import *
from .mcp import *

__all__ = []
for module in (_api, _paths, _limits, _terminal, _conversation, _security, _ui, _memory, _ocr, _todo, _auth, _uploads, _sub_agent, _custom_tools, _mcp):
    __all__ += getattr(module, "__all__", [])

del _api, _paths, _limits, _terminal, _conversation, _security, _ui, _memory, _ocr, _todo, _auth, _uploads, _sub_agent, _custom_tools, _mcp
