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

@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_reset_session(temp_logs: Path) -> None:
 # 1. Open first session
 label1 = "label1"
 session_logger.open_session(label=label1)
 
 subdirs = [d for d in temp_logs.iterdir() if d.is_dir()]
 assert len(subdirs) == 1
 session1_dir = subdirs[0]
 assert session1_dir.name.endswith(f"_{label1}")
 assert session_logger._comms_fh is not None
 
 # 2. Reset to second session
 time.sleep(1.1)
 
 label2 = "label2"
 session_logger.reset_session(label=label2)
 
 subdirs = sorted([d for d in temp_logs.iterdir() if d.is_dir()], key=lambda x: x.name)
 assert len(subdirs) == 2
 session2_dir = subdirs[1]
 assert session2_dir.name.endswith(f"_{label2}")
 assert session_logger._comms_fh is not None
 
 # Verify new handle points to new dir
 assert str(session2_dir) in str(Path(session_logger._comms_fh.name).resolve())
