"""
Project root discovery and PULSE home resolution.

Handles .pulse.yaml parsing, dev-mode detection, project hashing,
and pulse home/license path resolution. No brain or state paths here.
"""

import hashlib
import os
from pathlib import Path


def _load_pulse_yaml(project_root: Path) -> dict:
    """Load .pulse.yaml project config (simple key: value parser, no pyyaml needed).

    Supported keys: provider, model, brain_dir, state_dir, tier
    Lines starting with # are comments. Nested keys use dot notation (search.timeout: 5).
    """
    yaml_file = project_root / ".pulse.yaml"
    if not yaml_file.exists():
        return {}
    config = {}
    try:
        for line in yaml_file.read_text(encoding="utf-8").splitlines():
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            if ":" not in line:
                continue
            key, _, value = line.partition(":")
            key = key.strip()
            value = value.strip().strip("\"'")
            if value.lower() in ("true", "yes"):
                value = True
            elif value.lower() in ("false", "no"):
                value = False
            elif value.isdigit():
                value = int(value)
            config[key] = value
    except OSError:
        pass
    return config


# Cached project config from .pulse.yaml
_project_config: dict | None = None


def get_project_config() -> dict:
    """Get .pulse.yaml config for the current project (cached)."""
    global _project_config
    if _project_config is None:
        _project_config = _load_pulse_yaml(get_project_root())
    return _project_config


def _is_dev_mode() -> bool:
    """Check if CWD is inside the PULSE development repo.

    Dev mode = user is working in the PULSE repo itself.
    NOT dev mode = user is in any other project (even with editable install).
    """
    # Env override
    if os.environ.get("PULSE_DEV"):
        return True
    if os.environ.get("PULSE_INSTALLED"):
        return False
    # Check CWD: are we inside the PULSE dev repo?
    cwd = Path.cwd().resolve()
    for parent in [cwd] + list(cwd.parents):
        if (parent / "PULSE_OS.md").exists() and (parent / "pulse").is_dir():
            return True
    return False


def get_project_root() -> Path:
    """Find the root of the current project (dev repo or user project)."""
    curr = Path.cwd().resolve()
    for parent in [curr] + list(curr.parents):
        if (parent / ".git").exists() or (parent / "PULSE_OS.md").exists() or (parent / ".pulse.yaml").exists():
            return parent
    return curr


def get_project_hash() -> str:
    """Stable hash for the current project."""
    root = get_project_root()
    return hashlib.sha256(str(root).encode()).hexdigest()[:12]


def get_pulse_home() -> Path:
    """Return global ~/.pulse directory."""
    return Path.home() / ".pulse"


def get_license_file() -> Path:
    """Return path to license file: ~/.pulse/license.json."""
    return get_pulse_home() / "license.json"


def _has_project_marker(root: Path) -> bool:
    """Check if directory has a valid project marker."""
    return (
        (root / ".git").exists()
        or (root / ".pulse.yaml").exists()
        or (root / "PULSE_OS.md").exists()
    )
