# @pattern Template Method
"""
Khy OS: AI platform operating system with a built-in default app.

This package provides a Python CLI launcher that bootstraps and manages
a Node.js-based quantitative trading backend. The architecture is:

    Python CLI (entry point)
        -> Node.js backend (Express server + CLI REPL)
            -> Data sources (AKShare, TuShare, etc.)
            -> AI providers (Gemini, Groq, OpenRouter, etc.)
            -> SQLite/PostgreSQL database
            -> Vue.js frontend (optional)

Key features:
    - Multi-source market data aggregation (A-shares, crypto, forex)
    - AI-powered trading signal generation and strategy recommendations
    - Backtesting engine with historical data replay
    - Real-time portfolio tracking and risk management
    - Plugin system for custom strategies and data adapters
    - Web UI dashboard with professional TradingView-style charts

Install modes:
    pip install khy-os             # Core CLI + backend
    pip install khy-os[data]       # + Python data analysis (pandas, numpy)
    pip install khy-os[ml]         # + Machine learning strategies (sklearn, xgboost)
    pip install khy-os[full]       # Everything
    pip install khy-quant          # Legacy compatibility package name

Quick start:
    $ khy            # Launch interactive REPL
    $ khy server     # Start web server on port 8080
    $ khy data list  # Browse available data sources

Version history:
    1.0.4 - Open-source release with full documentation
"""
from pathlib import Path


def _detect_version() -> str:
    """Resolve the package version from a single source of truth.

    Order of authority:
      1. Installed distribution metadata (``importlib.metadata``) — correct for
         every ``pip install`` of ``khy-os`` / ``khy-quant``. It is derived from
         ``pyproject.toml`` at build time, so it can never drift from the release.
      2. ``pyproject.toml`` parsed from the source tree — covers raw checkouts
         that were never pip-installed (editable dev, bundled payloads). Parsed
         without a ``toml`` dependency to stay compatible with ``requires-python
         >= 3.8`` (``tomllib`` only lands in 3.11).
      3. ``"0.0.0"`` as an explicit "unknown" marker.

    The version is intentionally never hard-coded here: bumping
    ``pyproject.toml`` alone keeps this value correct, removing a silent
    version-drift bug class.
    """
    try:
        try:
            from importlib import metadata as _md  # Python 3.8+
        except ImportError:  # pragma: no cover - Python < 3.8 fallback
            import importlib_metadata as _md  # type: ignore
        for _dist in ("khy-os", "khy-quant"):
            try:
                return _md.version(_dist)
            except Exception:
                continue
    except Exception:
        pass

    here = Path(__file__).resolve()
    for _base in here.parents:
        pyproject = _base / "pyproject.toml"
        if not pyproject.is_file():
            continue
        try:
            in_project = False
            for raw in pyproject.read_text(encoding="utf-8").splitlines():
                line = raw.strip()
                if line.startswith("["):
                    in_project = line.lower().startswith("[project]")
                    continue
                if in_project and line.startswith("version") and "=" in line:
                    val = line.partition("=")[2].split("#", 1)[0].strip()
                    val = val.strip('"').strip("'")
                    if val:
                        return val
        except Exception:
            pass
        break  # nearest pyproject is authoritative; stop walking up
    return "0.0.0"


__version__ = _detect_version()

# Absolute path of this installed package — exported at the entry so any runtime
# can trace exactly where khy OS lives (pip install root or source checkout).
INSTALL_PATH: Path = Path(__file__).resolve().parent

__all__ = [
    "__version__",
    "INSTALL_PATH",
    "get_install_path",
    "get_install_root",
    "run_postinstall",
    "ensure_dev_environment",
    "configure_dev_environment",
]


def get_install_path() -> Path:
    """Return the absolute path of the installed ``khy_platform`` package."""
    return INSTALL_PATH


def get_install_root() -> Path:
    """Return the install root containing the Python package roots."""
    return INSTALL_PATH.parent


def run_postinstall(*args, **kwargs) -> int:
    """Install-phase cross-language runtime self-heal (see :mod:`devenv`).

    Lazy delegate so importing :mod:`khy_platform` stays cheap and free of
    subprocess/toolchain imports.
    """
    from khy_platform.devenv import run_postinstall as _impl
    return _impl(*args, **kwargs)


def ensure_dev_environment(*args, **kwargs) -> int:
    """Compile-phase dev-toolchain self-heal (see :mod:`devenv`)."""
    from khy_platform.devenv import ensure_dev_environment as _impl
    return _impl(*args, **kwargs)


# Alias matching the goal's "环境配置函数" wording.
configure_dev_environment = ensure_dev_environment
