"""Shared utilities for joyspace-pro pipeline and entry scripts.

Centralizes:
- Default output directory conventions (~/.joyclaw/data/)
- WSL mirror path support
"""

import os
import platform
import shutil
from pathlib import Path

# Stable user-level base directory for all pipeline outputs
JOYCLAW_DATA_DIR = Path(os.environ.get("JOYCLAW_DATA", str(Path.home() / ".joyclaw" / "data")))


def default_output_dir(subdir: str = "") -> Path:
    """Return the default output directory under ~/.joyclaw/data/<subdir>.

    Uses a stable user-level path that works across all platforms
    (Windows, macOS, WSL, OpenClaw). Override with JOYCLAW_DATA env var.

    Creates the directory if it doesn't exist.
    """
    base = JOYCLAW_DATA_DIR
    if subdir:
        base = base / subdir
    base.mkdir(parents=True, exist_ok=True)
    return base


def wsl_mirror_copy(src_path: str | Path, subdir: str = "") -> str | None:
    """Best-effort copy a file to D:/joyclaw_data/<subdir>/ for Windows-side pickup on WSL.

    Returns the mirrored path on success, None on failure or non-WSL.
    """
    try:
        uname = platform.uname().release.lower()
        if "microsoft" not in uname and "wsl" not in uname:
            return None

        mirror_base = Path("/mnt/d/joyclaw_data")
        if subdir:
            mirror_base = mirror_base / subdir
        mirror_base.mkdir(parents=True, exist_ok=True)

        src = Path(src_path)
        dest = mirror_base / src.name
        shutil.copy2(str(src), str(dest))
        return str(dest)
    except Exception:
        return None
