"""Shared path resolution for mldash managed environment."""

import os
import sys


def mldash_home():
    """Return the mldash home directory (~/.mldash or $MLDASH_HOME)."""
    return os.environ.get("MLDASH_HOME") or os.path.expanduser("~/.mldash")


def managed_venv_path():
    """Return the path to the managed venv directory."""
    return os.path.join(mldash_home(), "venv")


def managed_python_path():
    """Return the path to the managed venv's python, or None if it doesn't exist."""
    venv = managed_venv_path()
    if sys.platform == "win32":
        python = os.path.join(venv, "Scripts", "python.exe")
    else:
        python = os.path.join(venv, "bin", "python")
    return python if os.path.isfile(python) else None


def managed_pip_path():
    """Return the path to the managed venv's pip, or None if it doesn't exist."""
    venv = managed_venv_path()
    if sys.platform == "win32":
        pip = os.path.join(venv, "Scripts", "pip.exe")
    else:
        pip = os.path.join(venv, "bin", "pip")
    return pip if os.path.isfile(pip) else None


def models_dir():
    """Return the path to the mldash models directory (~/.mldash/models)."""
    return os.path.join(mldash_home(), "models")


def autocomplete_model_path():
    """Return the path to the autocomplete GGUF model file."""
    return os.path.join(models_dir(), "qwen2.5-coder-1.5b-q8_0.gguf")


def resolve_kernel_python():
    """Resolve which Python to use for the kernel.

    Priority:
      1. $MLDASH_PYTHON env var (power user escape hatch)
      2. ~/.mldash/venv/bin/python if it exists (managed venv)
      3. sys.executable (current behavior — fallback)

    Returns:
        (path, source) where source is one of "env", "managed", "system".
    """
    # 1. Explicit override
    env_python = os.environ.get("MLDASH_PYTHON")
    if env_python and os.path.isfile(env_python):
        return (env_python, "env")

    # 2. Managed venv
    managed = managed_python_path()
    if managed:
        return (managed, "managed")

    # 3. System fallback
    return (sys.executable, "system")
