"""
Local / global context resolution.

If a ``llmpm.json`` is found in the current working directory (or any parent)
the session runs in *local* mode:

  LLMPM_HOME  →  <project-root>/.llmpm/

Otherwise it falls back to *global* mode:

  LLMPM_HOME  →  ~/.llmpm/

The ``LLMPM_HOME`` environment variable overrides both.
"""

from __future__ import annotations

import os
from pathlib import Path


def find_llmpm_json() -> Path | None:
    """
    Walk up from CWD looking for ``llmpm.json``.

    Returns the absolute path to the file, or ``None`` if not found.
    """
    cwd = Path.cwd()
    for directory in [cwd, *cwd.parents]:
        candidate = directory / "llmpm.json"
        if candidate.is_file():
            return candidate
    return None


def get_home() -> Path:
    """
    Return the active LLMPM_HOME (not yet created):

    Priority:
      1. ``LLMPM_HOME`` environment variable
      2. ``<project-root>/.llmpm/`` when ``llmpm.json`` is found
      3. ``~/.llmpm/`` (global fallback)
    """
    env = os.environ.get("LLMPM_HOME")
    if env:
        return Path(env)
    llmpm_json = find_llmpm_json()
    if llmpm_json is not None:
        return llmpm_json.parent / ".llmpm"
    return Path.home() / ".llmpm"


def is_local() -> bool:
    """Return ``True`` when a ``llmpm.json`` is found in CWD or a parent."""
    return find_llmpm_json() is not None


def project_root() -> Path | None:
    """Return the directory that contains ``llmpm.json``, or ``None``."""
    llmpm_json = find_llmpm_json()
    return llmpm_json.parent if llmpm_json is not None else None
