# aider-watch-client config | 2026-04-20 @ Asia/Taipei
"""讀 ~/.aider-watch.env + 常數路徑。"""
from __future__ import annotations
import os
from pathlib import Path
from datetime import timezone, timedelta

HOME = Path.home()
WATCH_ROOT = HOME / "aider-watch"
BUFFER_DIR = WATCH_ROOT / "buffer"
LIVE_LOG = WATCH_ROOT / "live.log"
LOGS_DIR = WATCH_ROOT / "logs"
ENV_FILE = HOME / ".aider-watch.env"
TAIPEI = timezone(timedelta(hours=8))
_loaded = False


def load_env() -> None:
    global _loaded
    if _loaded or not ENV_FILE.exists():
        _loaded = True
        return
    for line in ENV_FILE.read_text().splitlines():
        s = line.strip()
        if not s or s.startswith("#") or "=" not in s:
            continue
        k, _, v = s.partition("=")
        os.environ.setdefault(k.strip(), v.strip())
    _loaded = True


def get(name: str, default: str = "", required: bool = False) -> str:
    load_env()
    v = os.environ.get(name, default)
    if required and not v:
        raise RuntimeError(f"{name} not set in {ENV_FILE}")
    return v


def ensure_dirs() -> None:
    for d in (WATCH_ROOT, BUFFER_DIR, LOGS_DIR):
        d.mkdir(parents=True, exist_ok=True)
