import os
import pytest
from datetime import datetime
from log_registry import LogRegistry

@pytest.fixture
def registry_setup(tmp_path):
    registry_path = tmp_path / "log_registry.toml"
    logs_dir = tmp_path / "logs"
    logs_dir.mkdir()
    registry = LogRegistry(str(registry_path))
    return registry, logs_dir

def test_auto_whitelist_keywords(registry_setup):
    registry, logs_dir = registry_setup
    session_id = "test_kw"
    session_dir = logs_dir / session_id
    session_dir.mkdir()
    
    # Create comms.log with ERROR
    comms_log = session_dir / "comms.log"
    comms_log.write_text("Some message\nAN ERROR OCCURRED\nMore text")
    
    registry.register_session(session_id, str(session_dir), datetime.now())
    registry.update_auto_whitelist_status(session_id)
    
    assert registry.is_session_whitelisted(session_id)
    assert "ERROR" in registry.data[session_id]["metadata"]["reason"]

def test_auto_whitelist_message_count(registry_setup):
    registry, logs_dir = registry_setup
    session_id = "test_msg_count"
    session_dir = logs_dir / session_id
    session_dir.mkdir()
    
    # Create comms.log with > 10 lines
    comms_log = session_dir / "comms.log"
    comms_log.write_text("\n".join(["msg"] * 15))
    
    registry.register_session(session_id, str(session_dir), datetime.now())
    registry.update_auto_whitelist_status(session_id)
    
    assert registry.is_session_whitelisted(session_id)
    assert registry.data[session_id]["metadata"]["message_count"] == 15

def test_auto_whitelist_large_size(registry_setup):
    registry, logs_dir = registry_setup
    session_id = "test_large"
    session_dir = logs_dir / session_id
    session_dir.mkdir()
    
    # Create large file (> 50KB)
    large_file = session_dir / "large.log"
    large_file.write_text("x" * 60000)
    
    registry.register_session(session_id, str(session_dir), datetime.now())
    registry.update_auto_whitelist_status(session_id)
    
    assert registry.is_session_whitelisted(session_id)
    assert "Large session size" in registry.data[session_id]["metadata"]["reason"]

def test_no_auto_whitelist_insignificant(registry_setup):
    registry, logs_dir = registry_setup
    session_id = "test_insignificant"
    session_dir = logs_dir / session_id
    session_dir.mkdir()
    
    # Small file, few lines, no keywords
    comms_log = session_dir / "comms.log"
    comms_log.write_text("hello\nworld")
    
    registry.register_session(session_id, str(session_dir), datetime.now())
    registry.update_auto_whitelist_status(session_id)
    
    assert not registry.is_session_whitelisted(session_id)
    assert registry.data[session_id]["metadata"]["message_count"] == 2
