"""Test monitoring engine."""

import sys
import time
from pathlib import Path
from datetime import datetime, timedelta

sys.path.insert(0, str(Path(__file__).parent.parent))

from unishell.core.monitoring import SimpleMonitoringEngine

print("=== Monitoring Engine Tests ===\n")

# Initialize
monitor = SimpleMonitoringEngine(max_logs=100)

print("=== Test 1: Log Execution Start ===")
log = monitor.log_execution_start("file.move", {"source": "/tmp/a.txt"})
print(f"Timestamp: {log.timestamp}")
print(f"Action: {log.action_id}")
print(f"Status: {log.status}")
print(f"Details: {log.details}")
print()

print("=== Test 2: Log Execution End ===")
time.sleep(0.1)
log = monitor.log_execution_end("file.move", {"destination": "/tmp/b.txt"})
print(f"Status: {log.status}")
print(f"Details: {log.details}")
print()

print("=== Test 3: Log Failure ===")
log = monitor.log_failure("file.delete", "File not found", {"path": "/tmp/missing.txt"})
print(f"Status: {log.status}")
print(f"Details: {log.details}")
print()

print("=== Test 4: Get Recent Events ===")
# Add more logs
monitor.log_execution_start("system.restart")
monitor.log_execution_end("system.restart")

recent = monitor.get_recent_events(limit=3)
print(f"Recent events (last 3):")
for log in recent:
    print(f"  - {log.action_id}: {log.status}")
print()

print("=== Test 5: Get Events by Action ===")
monitor.log_execution_start("file.move")
monitor.log_execution_end("file.move")

file_move_logs = monitor.get_events_by_action("file.move")
print(f"file.move events: {len(file_move_logs)}")
for log in file_move_logs:
    print(f"  - {log.status} at {log.timestamp}")
print()

print("=== Test 6: Get Events by Status ===")
failed_logs = monitor.get_events_by_status("failed")
print(f"Failed events: {len(failed_logs)}")
for log in failed_logs:
    print(f"  - {log.action_id}: {log.details.get('error')}")
print()

print("=== Test 7: Get Events Since ===")
since_time = datetime.now() - timedelta(seconds=1)
recent_logs = monitor.get_events_since(since_time)
print(f"Events in last second: {len(recent_logs)}")
print()

print("=== Test 8: Get Statistics ===")
stats = monitor.get_statistics()
print(f"Total events: {stats['total_events']}")
print(f"Started: {stats['started']}")
print(f"Success: {stats['success']}")
print(f"Failed: {stats['failed']}")
print(f"Success rate: {stats['success_rate']:.2%}")
print()

print("=== Test 9: Max Logs Limit ===")
initial_count = len(monitor.get_recent_events(limit=1000))
print(f"Current logs: {initial_count}")

# Add logs beyond max
for i in range(50):
    monitor.log_execution_start(f"test.action{i}")

final_count = len(monitor.get_recent_events(limit=1000))
print(f"After adding 50: {final_count}")
print(f"Max logs enforced: {final_count <= 100}")
print()

print("=== Test 10: Clear Logs ===")
cleared = monitor.clear_logs()
print(f"Cleared {cleared} logs")
print(f"Remaining: {len(monitor.get_recent_events(limit=1000))}")
print()

print("[SUCCESS] Monitoring engine tests complete!")
