import os
import shutil
import pytest
from pathlib import Path
from datetime import datetime, timedelta
from log_registry import LogRegistry
from log_pruner import LogPruner

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

def test_prune_old_insignificant_logs(pruner_setup):
    pruner, registry, logs_dir = pruner_setup
    
    # 1. Old and small (insignificant) -> should be pruned
    session_id_old_small = "old_small"
    dir_old_small = logs_dir / session_id_old_small
    dir_old_small.mkdir()
    (dir_old_small / "comms.log").write_text("small") # < 2KB
    registry.register_session(session_id_old_small, str(dir_old_small), datetime.now() - timedelta(days=2))
    
    # 2. Old and large (significant) -> should NOT be pruned
    session_id_old_large = "old_large"
    dir_old_large = logs_dir / session_id_old_large
    dir_old_large.mkdir()
    (dir_old_large / "comms.log").write_text("x" * 3000) # > 2KB
    registry.register_session(session_id_old_large, str(dir_old_large), datetime.now() - timedelta(days=2))
    
    # 3. Recent and small -> should NOT be pruned
    session_id_recent_small = "recent_small"
    dir_recent_small = logs_dir / session_id_recent_small
    dir_recent_small.mkdir()
    (dir_recent_small / "comms.log").write_text("small")
    registry.register_session(session_id_recent_small, str(dir_recent_small), datetime.now() - timedelta(hours=2))
    
    # 4. Old and whitelisted -> should NOT be pruned
    session_id_old_whitelisted = "old_whitelisted"
    dir_old_whitelisted = logs_dir / session_id_old_whitelisted
    dir_old_whitelisted.mkdir()
    (dir_old_whitelisted / "comms.log").write_text("small")
    registry.register_session(session_id_old_whitelisted, str(dir_old_whitelisted), datetime.now() - timedelta(days=2))
    registry.update_session_metadata(session_id_old_whitelisted, 0, 0, 0, True, "Manual")
    
    pruner.prune()
    
    assert not dir_old_small.exists()
    assert dir_old_large.exists()
    assert dir_recent_small.exists()
    assert dir_old_whitelisted.exists()
