"""
Memory Leak Detection Test
"""
import os
import psutil
import pytest
from altrus.core.kernel import AltrusKernel
from altrus.core.intent.intent import Intent, IntentPriority
from altrus.core.registry.module import Module
from altrus.core.observability.server import stop_metrics_server

def get_process_memory():
    process = psutil.Process(os.getpid())
    return process.memory_info().rss / (1024 * 1024)  # MB

def test_memory_leak_intent_submission(tmp_path):
    """Submit many intents and check for memory growth"""
    stop_metrics_server()
    kernel = AltrusKernel(storage_dir=tmp_path)

    # Register handler
    module = Module("m1", "M1", "1.0", ["task.a"])
    kernel.registry.register(module)
    kernel.start()

    # Baseline
    initial_mem = get_process_memory()
    print(f"Initial Memory: {initial_mem:.2f} MB")

    # High volume submission
    for i in range(1000):
        intent = Intent(f"i{i}", "task", "task.a", IntentPriority.NORMAL)
        kernel.intent_engine.submit_intent(intent)

    # Final memory
    final_mem = get_process_memory()
    print(f"Final Memory: {final_mem:.2f} MB")

    # Growth should be reasonable (< 20MB for 1000 intents)
    # Each intent is roughly 1-2KB in dict form
    # Memory growth might be higher due to Python's object allocations,
    # but shouldn't be hundreds of MBs.
    assert final_mem - initial_mem < 50, f"Significant memory growth: {final_mem - initial_mem:.2f} MB"

    kernel.shutdown()
    stop_metrics_server()
