"""Tests for the live_gui_workspace fixture (Phase 3, Task 3.2)."""
import importlib.util
import shutil
from pathlib import Path


def test_live_gui_workspace_is_path(live_gui_workspace) -> None:
 """The live_gui_workspace fixture yields a Path object."""
 assert isinstance(live_gui_workspace, Path)


def test_live_gui_workspace_exists(live_gui_workspace) -> None:
 """The workspace path was created and exists on disk."""
 assert live_gui_workspace.exists()


def test_live_gui_workspace_is_a_directory(live_gui_workspace) -> None:
 """The workspace is a directory (not a file)."""
 assert live_gui_workspace.is_dir()


def test_live_gui_workspace_in_tests_artifacts(live_gui_workspace) -> None:
 """The workspace is under tests/artifacts/ (per-run timestamped folder), NOT in the system temp dir."""
 path_str = str(live_gui_workspace).replace("\\", "/")
 assert "tests/artifacts/live_gui_workspace_" in path_str, f"Workspace not in tests/artifacts/: {live_gui_workspace}"
 assert "temp" not in path_str.lower() and "tmp" not in path_str.lower(), f"Workspace should NOT be in tmp dir: {live_gui_workspace}"


def test_live_gui_workspace_writable(live_gui_workspace) -> None:
 """Tests can write to the workspace."""
 test_file = live_gui_workspace / "test_write.txt"
 test_file.write_text("hello", encoding="utf-8")
 assert test_file.read_text(encoding="utf-8") == "hello"


def test_live_gui_workspace_recreates_missing_workspace(live_gui) -> None:
 """[TDD red] Captures the xdist race in live_gui_workspace: when the owner
 worker's live_gui teardown rmtree's the shared workspace between client
 workers' tests, a client worker calling live_gui_workspace must recreate
 the directory before returning the path. The current fixture returns the
 path without mkdir, so the returned path does not exist after rmtree.
 NOTE: on Windows, the live_gui subprocess holds the live workspace as its
 CWD, which blocks shutil.rmtree on the live path. We instead point the
 handle at a fresh, never-existed path under tests/artifacts/ to simulate
 the post-teardown state deterministically on all platforms.
 """
 import time
 fake_workspace = Path(f"tests/artifacts/_live_gui_workspace_race_sim_{int(time.time() * 1000000)}")
 assert not fake_workspace.exists(), f"sanity: fake workspace must not exist pre-call: {fake_workspace}"
 original_workspace = live_gui._workspace
 live_gui._workspace = fake_workspace
 try:
  spec = importlib.util.spec_from_file_location(
   "tests.conftest",
   str(Path(__file__).parent / "conftest.py"),
  )
  conftest = importlib.util.module_from_spec(spec)
  spec.loader.exec_module(conftest)
  result = conftest.live_gui_workspace.__wrapped__(live_gui)
  assert result.exists(), f"live_gui_workspace did not recreate missing workspace at {result}"
 finally:
  live_gui._workspace = original_workspace
  if fake_workspace.exists():
   shutil.rmtree(fake_workspace, ignore_errors=True)
