import os
import shutil
import pytest
from pathlib import Path
from datetime import datetime
from unittest.mock import patch
import session_logger
import tomllib

@pytest.fixture
def temp_logs(tmp_path):
    # Mock _LOG_DIR in session_logger
    original_log_dir = session_logger._LOG_DIR
    session_logger._LOG_DIR = tmp_path / "logs"
    session_logger._LOG_DIR.mkdir(parents=True, exist_ok=True)
    
    # Mock _SCRIPTS_DIR
    original_scripts_dir = session_logger._SCRIPTS_DIR
    session_logger._SCRIPTS_DIR = tmp_path / "scripts" / "generated"
    session_logger._SCRIPTS_DIR.mkdir(parents=True, exist_ok=True)
    
    yield tmp_path / "logs"
    
    # Cleanup: Close handles if open
    session_logger.close_session()
    session_logger._LOG_DIR = original_log_dir
    session_logger._SCRIPTS_DIR = original_scripts_dir

def test_open_session_creates_subdir_and_registry(temp_logs):
    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)
