"""
Dual-mode path resolution for PULSE.

Dev mode (us):     Brain data in repo at ./Hippocampus/
Installed mode:    Brain data at ~/.pulse/brain/ (global per-user, all projects)

Detection: If we're inside a git repo with PULSE_OS.md, we're in dev mode.

Brain/state path resolution, user consent, and brain scaffold initialization.
Low-level project/home resolution lives in paths_resolution.py.
"""

import json
import os
import sys
from datetime import datetime, timezone
from pathlib import Path

from pulse.core.paths_resolution import (
    _has_project_marker,
    _is_dev_mode,
    _load_pulse_yaml,
    get_license_file,
    get_project_config,
    get_project_hash,
    get_project_root,
    get_pulse_home,
)

from pulse.core.paths_brain_init import (
    ConsentDeclined, NoProjectRoot, BRAIN_SCAFFOLD, MINIMAL_ANTI_PATTERNS_JSON,
    _check_consent, init_user_brain,
)

__all__ = [
    # from paths_resolution
    "_load_pulse_yaml",
    "get_project_config",
    "_is_dev_mode",
    "get_project_root",
    "get_project_hash",
    "get_pulse_home",
    "get_license_file",
    "_has_project_marker",
    # local
    "get_project_dir",
    "get_brain_dir",
    "get_state_dir",
    "get_root_dir",
    "_check_consent",
    "init_user_brain",
    "ConsentDeclined",
    "NoProjectRoot",
]


def get_project_dir() -> Path:
    """Return the isolated project directory in ~/.pulse/projects/<hash>
    unless in dev mode, then return the repo root."""
    if _is_dev_mode():
        # CWD is inside the PULSE dev repo — find the repo root
        cwd = Path.cwd().resolve()
        for parent in [cwd] + list(cwd.parents):
            if (parent / "PULSE_OS.md").exists() and (parent / "pulse").is_dir():
                return parent
        return cwd
    return get_pulse_home() / "projects" / get_project_hash()


def get_brain_dir() -> Path:
    """Return brain directory based on mode. Priority: env > .pulse.yaml > default."""
    env = os.environ.get("PULSE_BRAIN_DIR")
    if env:
        return Path(env)
    yaml_val = get_project_config().get("brain_dir")
    if yaml_val:
        return Path(yaml_val)
    if _is_dev_mode():
        return get_project_dir() / "Hippocampus"
    return get_project_dir() / "brain"


def get_state_dir() -> Path:
    """Return state directory based on mode. Priority: env > .pulse.yaml > default."""
    env = os.environ.get("PULSE_STATE_DIR")
    if env:
        return Path(env)
    yaml_val = get_project_config().get("state_dir")
    if yaml_val:
        return Path(yaml_val)
    if _is_dev_mode():
        return get_project_dir() / "state"
    return get_project_dir() / "state"


def get_root_dir() -> Path:
    """Return project root (dev) or isolated project dir (installed)."""
    env = os.environ.get("PULSE_ROOT")
    if env:
        return Path(env)
    return get_project_dir()


