import pytest
import tomllib
from pathlib import Path
from typing import Generator
from src import session_logger

@pytest.fixture
def temp_logs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Generator[Path, None, None]:
# Ensure closed before starting
 session_logger.close_session()
 monkeypatch.setattr(session_logger, "_comms_fh", None)
 
 log_dir = tmp_path / "logs"
 scripts_dir = tmp_path / "scripts" / "generated"
 log_dir.mkdir(parents=True, exist_ok=True)
 scripts_dir.mkdir(parents=True, exist_ok=True)
 
 from src import paths
 monkeypatch.setattr(paths, "get_logs_dir", lambda: log_dir)
 monkeypatch.setattr(paths, "get_scripts_dir", lambda: scripts_dir)
 
 yield log_dir
 # Cleanup: Close handles if open
 session_logger.close_session()

def test_open_session_creates_subdir_and_registry(temp_logs: Path) -> None:

 label = "test-label"
 # We can't easily mock datetime.datetime.now() because it's a built-in
 # but we can check the resulting directory name pattern
 session_logger.open_session(label=label)
 # Check that a subdirectory was created
 subdirs = list(temp_logs.iterdir())
 # One is the log_registry.toml, one is the session dir
 session_dirs = [d for d in subdirs if d.is_dir()]
 assert len(session_dirs) == 1
 session_dir = session_dirs[0]
 assert session_dir.name.endswith(f"_{label}")
 # Check for log files
 assert (session_dir / "comms.log").exists()
 assert (session_dir / "toolcalls.log").exists()
 assert (session_dir / "apihooks.log").exists()
 assert (session_dir / "clicalls.log").exists()
 # Check registry
 registry_path = temp_logs / "log_registry.toml"
 assert registry_path.exists()
 with open(registry_path, "rb") as f:
  data = tomllib.load(f)
  assert session_dir.name in data
  assert data[session_dir.name]["path"] == str(session_dir)
