"""Unit tests for system default-app opening helper."""

from __future__ import annotations

import subprocess
from pathlib import Path
from unittest.mock import Mock

import pytest

from cascade_fm.system_open import open_in_default_app


def test_open_in_default_app_missing_path(tmp_path: Path) -> None:
    """Opening missing files should raise FileNotFoundError."""
    with pytest.raises(FileNotFoundError):
        open_in_default_app(tmp_path / "missing.txt")


def test_open_in_default_app_linux(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    """Linux should invoke xdg-open."""
    file_path = tmp_path / "file.txt"
    file_path.write_text("x")

    run_mock = Mock()
    monkeypatch.setattr("cascade_fm.system_open.platform.system", lambda: "Linux")
    monkeypatch.setattr("cascade_fm.system_open.subprocess.run", run_mock)

    open_in_default_app(file_path)

    run_mock.assert_called_once_with(["xdg-open", str(file_path)], check=True)


def test_open_in_default_app_macos(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    """macOS should invoke open."""
    file_path = tmp_path / "file.txt"
    file_path.write_text("x")

    run_mock = Mock()
    monkeypatch.setattr("cascade_fm.system_open.platform.system", lambda: "Darwin")
    monkeypatch.setattr("cascade_fm.system_open.subprocess.run", run_mock)

    open_in_default_app(file_path)

    run_mock.assert_called_once_with(["open", str(file_path)], check=True)


def test_open_in_default_app_windows(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    """Windows should invoke os.startfile."""
    file_path = tmp_path / "file.txt"
    file_path.write_text("x")

    startfile_mock = Mock()
    monkeypatch.setattr("cascade_fm.system_open.platform.system", lambda: "Windows")
    monkeypatch.setattr("cascade_fm.system_open.os.startfile", startfile_mock, raising=False)

    open_in_default_app(file_path)

    startfile_mock.assert_called_once_with(str(file_path))


def test_open_in_default_app_subprocess_failure(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    """Subprocess launcher errors should propagate."""
    file_path = tmp_path / "file.txt"
    file_path.write_text("x")

    monkeypatch.setattr("cascade_fm.system_open.platform.system", lambda: "Linux")
    monkeypatch.setattr(
        "cascade_fm.system_open.subprocess.run",
        Mock(side_effect=subprocess.CalledProcessError(1, ["xdg-open"])),
    )

    with pytest.raises(subprocess.CalledProcessError):
        open_in_default_app(file_path)
