"""Runtime path helpers for Axiom.

Two distinct path concepts live here:

  get_project_root()   — the current *project's* root directory (.git / .neut anchor)
  get_user_state_dir() — user-global state, e.g. ~/.axi/ or ~/.neut/

Never derive runtime paths from ``axiom.__init__.REPO_ROOT``.  That value
is resolved at import time relative to the installed package's ``__file__``,
which points inside ``site-packages/`` for wheel installs.  Use these helpers
instead — they resolve relative to the *working directory* and active branding.

Project-local directories (e.g. ``.neut/publisher/``) should be anchored with
``get_project_root() / ".neut" / ...``.  User-global directories (credentials,
settings, services) should be anchored with ``get_user_state_dir() / ...``.
"""

from __future__ import annotations

import os
from pathlib import Path

from axiom.infra.branding import get_branding


def get_project_root(start: Path | None = None) -> Path:
    """Return the project root directory for the current working context.

    Resolution order:
    1. ``AXIOM_ROOT`` environment variable (explicit override — always wins)
    2. Walk up from *start* (default: ``Path.cwd()``) looking for ``.git``
       or ``.neut`` — returns the first directory that has either.
    3. Fall back to *start* (i.e. ``cwd``) if no anchor is found.

    This is safe for both editable (``pip install -e .``) and wheel installs
    because it never reads ``__file__``.
    """
    env_root = os.environ.get("AXIOM_ROOT")
    if env_root:
        return Path(env_root).resolve()

    base = (start or Path.cwd()).resolve()
    for candidate in [base, *base.parents]:
        if (candidate / ".git").exists() or (candidate / ".neut").exists():
            return candidate
    return base


def get_user_state_dir() -> Path:
    """Return the user-global state directory, branding-aware.

    * Axiom standalone  →  ``~/.axi/``
    * NeutronOS         →  ``~/.neut/``

    The directory is created on first access.  Its name comes from the active
    branding's ``cli_name`` field, so domain products automatically get their
    own isolated state tree without any code changes.
    """
    state_dir = Path.home() / f".{get_branding().cli_name}"
    state_dir.mkdir(parents=True, exist_ok=True)
    return state_dir
