"""Filesystem path helpers + tiny JSON load/save utilities.

All paths are derived from ``config.SAMBA_SHARE`` so swapping the share
root only requires changing one env var.
"""

import json
import os

import config


def image_root(image_type):
    """Return the root directory for an image type."""
    return os.path.join(config.SAMBA_SHARE, image_type)


def deploy_path(image_type):
    """Return the Deploy directory for an image type."""
    return os.path.join(config.SAMBA_SHARE, image_type, "Deploy")


def unattend_path(image_type):
    """Return the unattend.xml path for an image type."""
    return os.path.join(deploy_path(image_type), "FlatUnattendW10.xml")


def control_path(image_type):
    """Return the Deploy/Control directory for an image type."""
    return os.path.join(deploy_path(image_type), "Control")


def tools_path(image_type):
    """Return the Tools directory for an image type."""
    return os.path.join(config.SAMBA_SHARE, image_type, "Tools")


def load_json(filepath):
    """Parse a JSON file and return its contents, or [] on failure."""
    try:
        with open(filepath, "r", encoding="utf-8-sig") as fh:
            return json.load(fh)
    except (OSError, json.JSONDecodeError):
        return []


def save_json(filepath, data):
    """Write data as pretty-printed JSON, creating parent dirs as needed."""
    os.makedirs(os.path.dirname(filepath), exist_ok=True)
    with open(filepath, "w", encoding="utf-8") as fh:
        json.dump(data, fh, indent=2, ensure_ascii=False)
        fh.write("\n")


def resolve_destination(dest_dir, image_type):
    """Convert a Windows ``*destinationdir*`` path to a Linux filesystem path.

    Replaces the placeholder + backslashes, prepends
    ``SAMBA_SHARE/image_type/``, then resolves symlinks so shared dirs
    are followed.
    """
    if not dest_dir:
        return ""
    path = dest_dir
    lower = path.lower()
    idx = lower.find("*destinationdir*")
    if idx != -1:
        path = path[idx + len("*destinationdir*"):]
    path = path.replace("\\", "/").lstrip("/")
    full = os.path.join(config.SAMBA_SHARE, image_type, path)
    try:
        full = os.path.realpath(full)
    except OSError:
        pass
    return full
