from __future__ import annotations

import os
from pathlib import Path


def _resolve_app_home() -> Path:
    configured = os.getenv("FLOW_XHS_HOME")
    if configured:
        return Path(configured).expanduser().resolve()
    return (Path.home() / ".flow_xhs").resolve()


APP_HOME = _resolve_app_home()
SCHEMA_DIR = APP_HOME / "schemas"
LOG_DIR = APP_HOME / "logs"
OUTPUT_DIR = APP_HOME / "outputs"
DB_FILE = APP_HOME / "flow_xhs.db"


def ensure_runtime_dirs() -> None:
    APP_HOME.mkdir(parents=True, exist_ok=True)
    LOG_DIR.mkdir(parents=True, exist_ok=True)
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)


def configure_legacy_data_paths() -> None:
    """Force legacy modules to use CLI runtime paths.

    Existing modules import DB path at module level, so both origins must be patched.
    """
    import flow_xhs.runtime.config as common_config
    import flow_xhs.runtime.database.manager as db_manager

    common_config.APP_DATA_DIR = APP_HOME
    common_config.LOG_DIR = LOG_DIR
    common_config.LOG_FILE = LOG_DIR / "app.log"
    common_config.DB_FILE = DB_FILE
    db_manager.DB_FILE = DB_FILE
