from __future__ import annotations

import os
from pathlib import Path

# Cache the store directory to ensure consistency within the same process
# This prevents issues with Microsoft Store Python's LOCALAPPDATA virtualization
# where the same environment variable might return different values at different times
_STORE_DIR_CACHE: Path | None = None


def get_store_dir(*, create: bool = True) -> Path:
    """
    Resolve the root directory used to store AutoPromptLab2 runtime/session data.

    The resolved path is cached on first call to ensure consistency within the same
    Python process, preventing issues with environment variable changes or
    Microsoft Store Python's LOCALAPPDATA virtualization.

    Default behavior intentionally prefers a short, user-scoped directory to reduce
    the risk of Windows long-path checkout failures.

    Override:
    - AUTOPROMPTLAB2_DATA_DIR: Explicit data directory path.
    """
    global _STORE_DIR_CACHE

    # Return cached value if available
    if _STORE_DIR_CACHE is not None:
        if create and not _STORE_DIR_CACHE.exists():
            _STORE_DIR_CACHE.mkdir(parents=True, exist_ok=True)
        return _STORE_DIR_CACHE

    # Resolve store directory
    explicit = os.getenv("AUTOPROMPTLAB2_DATA_DIR")
    if explicit:
        store_dir = Path(explicit)
    else:
        local_app_data = os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
        if local_app_data:
            store_dir = Path(local_app_data) / "AutoPromptLab2"
        else:
            store_dir = Path.home() / ".autopromptlab2"

    # Cache the resolved path
    _STORE_DIR_CACHE = store_dir

    if create:
        store_dir.mkdir(parents=True, exist_ok=True)
    return store_dir


def _reset_store_dir_cache() -> None:
    """
    Reset the cached store directory. For internal use only (e.g., unit tests).

    WARNING: This function should NOT be called in production code. It exists
    solely for testing purposes to allow tests to verify behavior with different
    AUTOPROMPTLAB2_DATA_DIR values.
    """
    global _STORE_DIR_CACHE
    _STORE_DIR_CACHE = None

