import os
import platform
from pathlib import Path


def _read_bool_env(name: str, default: bool) -> bool:
    raw = os.getenv(name)
    if raw is None:
        return default
    text = str(raw).strip().lower()
    if text in {"1", "true", "yes", "on"}:
        return True
    if text in {"0", "false", "no", "off"}:
        return False
    return default


def get_app_data_dir(app_name="FlowXHS"):
    """
    Get the platform-specific user data directory.
    """
    system = platform.system()
    if system == "Windows":
        return Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming")) / app_name
    elif system == "Darwin":
        return Path.home() / "Library" / "Application Support" / app_name
    else:
        # Linux / Unix
        return Path.home() / ".local" / "share" / app_name


# Initialize paths
APP_DATA_DIR = get_app_data_dir()
try:
    APP_DATA_DIR.mkdir(parents=True, exist_ok=True)
except PermissionError:
    # Sandbox-friendly fallback for restricted environments (tests/CI).
    APP_DATA_DIR = Path.cwd() / ".flow_xhs_data"
    APP_DATA_DIR.mkdir(parents=True, exist_ok=True)

# Database path
DB_FILE = APP_DATA_DIR / "flow_xhs.db"

# Log path
LOG_DIR = APP_DATA_DIR / "logs"
LOG_DIR.mkdir(parents=True, exist_ok=True)
LOG_FILE = LOG_DIR / "app.log"

# --- 调试配置 ---
# 默认行为：无头（生产）
# 开发调试可通过环境变量强制有头：
# - FLOW_XHS_HEADFUL=1
# - BROWSER_HEADFUL=1
BROWSER_HEADLESS = _read_bool_env("BROWSER_HEADLESS", True)
_BROWSER_HEADFUL_FORCED = _read_bool_env("FLOW_XHS_HEADFUL", False) or _read_bool_env("BROWSER_HEADFUL", False)


def is_browser_headful_forced() -> bool:
    return _BROWSER_HEADFUL_FORCED


def resolve_browser_headless(requested: bool | None = None) -> bool:
    if _BROWSER_HEADFUL_FORCED:
        return False
    if requested is None:
        return BROWSER_HEADLESS
    return bool(requested)


def resolve_login_mode_headless(mode: str) -> bool:
    normalized_mode = str(mode or "").strip().lower()
    if normalized_mode == "local":
        # Local login is interactive by design.
        return resolve_browser_headless(False)
    if normalized_mode == "remote":
        # Remote login should mirror local browser environment as closely as possible.
        # The only intended difference is remote screenshot handoff, not a weaker
        # headless fingerprint.
        return resolve_browser_headless(None)
    return resolve_browser_headless()

# --- 浏览器环境配置 ---
# 建议与账号真实访问地区保持一致，减少环境指纹漂移。
BROWSER_LOCALE = os.getenv("BROWSER_LOCALE", "zh-CN")
BROWSER_TIMEZONE = os.getenv("BROWSER_TIMEZONE", "Asia/Shanghai")
