"""
Atomizer Path Configuration

Provides intelligent path resolution for Atomizer core modules and directories.
This module can be imported from anywhere in the project hierarchy.
"""

from pathlib import Path
import sys


def get_atomizer_root() -> Path:
    """
    Get the Atomizer project root directory.

    This function intelligently locates the root by looking for marker files
    that uniquely identify the Atomizer project root.

    Returns:
        Path: Absolute path to Atomizer root directory

    Raises:
        RuntimeError: If Atomizer root cannot be found
    """
    # Start from this file's location
    current = Path(__file__).resolve().parent

    # Marker files that uniquely identify Atomizer root
    markers = [
        'optimization_engine',  # Core module directory
        'studies',              # Studies directory
        'README.md'             # Project README
    ]

    # Walk up the directory tree looking for all markers
    max_depth = 10  # Prevent infinite loop
    for _ in range(max_depth):
        # Check if all markers exist at this level
        if all((current / marker).exists() for marker in markers):
            return current

        # Move up one directory
        parent = current.parent
        if parent == current:  # Reached filesystem root
            break
        current = parent

    raise RuntimeError(
        "Could not locate Atomizer root directory. "
        "Make sure you're running from within the Atomizer project."
    )


def setup_python_path():
    """
    Add Atomizer root to Python path if not already present.

    This allows imports like `from optimization_engine.core.runner import ...`
    to work from anywhere in the project.
    """
    root = get_atomizer_root()
    root_str = str(root)

    if root_str not in sys.path:
        sys.path.insert(0, root_str)


# Core directories (lazy-loaded)
_ROOT = None

def root() -> Path:
    """Get Atomizer root directory."""
    global _ROOT
    if _ROOT is None:
        _ROOT = get_atomizer_root()
    return _ROOT


def optimization_engine() -> Path:
    """Get optimization_engine directory."""
    return root() / 'optimization_engine'


def studies() -> Path:
    """Get studies directory."""
    return root() / 'studies'


def tests() -> Path:
    """Get tests directory."""
    return root() / 'tests'


def docs() -> Path:
    """Get docs directory."""
    return root() / 'docs'


def plugins() -> Path:
    """Get plugins directory."""
    return optimization_engine() / 'plugins'


# Common files
def readme() -> Path:
    """Get README.md path."""
    return root() / 'README.md'


def roadmap() -> Path:
    """Get development roadmap path."""
    return root() / 'DEVELOPMENT_ROADMAP.md'


# Convenience function for scripts
def ensure_imports():
    """
    Ensure Atomizer modules can be imported.

    Call this at the start of any script to ensure proper imports:

    ```python
    import atomizer_paths
    atomizer_paths.ensure_imports()

    # Now you can import Atomizer modules
    from optimization_engine.core.runner import OptimizationRunner
    ```
    """
    setup_python_path()


if __name__ == '__main__':
    # Self-test
    print("Atomizer Path Configuration")
    print("=" * 60)
    print(f"Root:                {root()}")
    print(f"Optimization Engine: {optimization_engine()}")
    print(f"Studies:             {studies()}")
    print(f"Tests:               {tests()}")
    print(f"Docs:                {docs()}")
    print(f"Plugins:             {plugins()}")
    print("=" * 60)
    print("\nAll paths resolved successfully!")
