"""Platform-independent paths for Mariner."""

import os
import pathlib
import platform
import subprocess

import platformdirs

_APP_NAME = "mariner"


def exists_or_create(path: str | pathlib.Path) -> pathlib.Path:
    """Check if path exists. If not, create it.

    Args:
      path: Path to check.

    Returns:
      Resulting path.

    """
    if not isinstance(path, pathlib.Path):
        path = pathlib.Path(path)
    path = path.expanduser()

    directory = path.parent if path.suffix else path
    directory.mkdir(parents=True, exist_ok=True)

    return path


def open_with_default_app(path: str, *, verbose: bool = False) -> None:
    """Open file in OS's default application.

    Args:
        path: Path to the file.
        verbose: Print verbose output.

    """
    if platform.system() == "Linux":
        if verbose:
            subprocess.run(["xdg-open", path], check=False)
        else:
            with open(os.devnull) as devnull:
                subprocess.run(
                    ["xdg-open", path],
                    stdout=devnull,
                    stderr=devnull,
                    check=False,
                )
    elif platform.system() == "Windows":
        os.startfile(path)  # type: ignore[attr-defined]  # Windows-only


def cache() -> pathlib.Path:
    """Cache path for the application."""
    return pathlib.Path(platformdirs.user_cache_dir(_APP_NAME))


def config() -> pathlib.Path:
    """Configuration path for the application."""
    return pathlib.Path(platformdirs.user_config_dir(_APP_NAME))


def data() -> pathlib.Path:
    """Data path for the application."""
    return pathlib.Path(platformdirs.user_data_dir(_APP_NAME))


def user_definitions() -> pathlib.Path:
    """User-managed tracker definitions directory."""
    return config() / "definitions"


def download() -> pathlib.Path:
    """User's download path."""
    return pathlib.Path("~/Downloads").expanduser()


def log() -> pathlib.Path:
    """Log path for the application."""
    return pathlib.Path(platformdirs.user_log_dir(_APP_NAME))
