"""Core functional tests for unified metrics system.

These tests were generated by an improved test agent after learning from
feedback about test quality and CI compatibility.
"""

import tempfile
from pathlib import Path

from pyeye.unified_metrics import UnifiedMetricsCollector


def test_session_workflow_basic():
    """Test basic session lifecycle: start -> record operations -> end."""
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        collector = UnifiedMetricsCollector(storage_dir=temp_path)

        # Start session
        session_id = collector.start_session(
            session_type="test", metadata={"test": "basic_workflow"}
        )

        # Record some operations
        collector.record_mcp_operation("find_symbol", session_id)
        collector.record_mcp_operation("find_references", session_id)
        collector.record_grep_operation(session_id)

        # Verify session is active
        active_sessions = collector.get_active_sessions()
        assert session_id in active_sessions
        assert active_sessions[session_id]["session_type"] == "test"
        assert active_sessions[session_id]["mcp_operations"]["find_symbol"] == 1
        assert active_sessions[session_id]["mcp_operations"]["find_references"] == 1
        assert active_sessions[session_id]["grep_operations"] == 1
        assert active_sessions[session_id]["total_operations"] == 3

        # End session
        final_metrics = collector.end_session(session_id)

        # Verify session moved to completed
        active_sessions = collector.get_active_sessions()
        assert session_id not in active_sessions

        # Verify final metrics include statistics
        assert final_metrics["session_id"] == session_id
        assert final_metrics["end_time"] is not None
        assert "statistics" in final_metrics
        assert final_metrics["statistics"]["mcp_operations_count"] == 2
        assert final_metrics["statistics"]["grep_operations_count"] == 1
        assert final_metrics["statistics"]["mcp_adoption_rate"] == 2 / 3  # 2 MCP ops out of 3 total


def test_session_hierarchy_parent_child_relationships():
    """Test session hierarchy with parent-child relationships."""
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        collector = UnifiedMetricsCollector(storage_dir=temp_path)

        # Create main session
        main_session_id = collector.start_session(session_type="main", metadata={"role": "parent"})

        # Create subagent sessions with main as parent
        subagent1_id = collector.start_session(
            session_type="subagent", parent_session=main_session_id, metadata={"role": "child1"}
        )

        # Small delay for Windows file system to sync
        # Even with filelock, Windows NTFS can have brief delays in file visibility
        # This is a known issue with rapid file operations on Windows
        import time

        time.sleep(0.05)  # 50ms delay

        subagent2_id = collector.start_session(
            session_type="subagent", parent_session=main_session_id, metadata={"role": "child2"}
        )

        # Get session tree
        tree = collector.get_session_tree()

        # Verify tree structure
        assert len(tree) == 1  # Only one root session
        assert main_session_id in tree

        # Verify main session properties
        main_session = tree[main_session_id]
        assert main_session["parent_session"] is None
        assert main_session["session_type"] == "main"
        assert main_session["metadata"]["role"] == "parent"

        # Verify children
        assert "children" in main_session
        assert len(main_session["children"]) == 2

        # Extract child session IDs from tree
        child_ids = {child["session_id"] for child in main_session["children"]}
        assert subagent1_id in child_ids
        assert subagent2_id in child_ids

        # Verify child properties
        for child in main_session["children"]:
            assert child["parent_session"] == main_session_id
            assert child["session_type"] == "subagent"
            assert child["metadata"]["role"] in ["child1", "child2"]


def test_persistence_across_instances():
    """Test that metrics persist across different collector instances."""
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)

        # First collector instance - create session and record operations
        collector1 = UnifiedMetricsCollector(storage_dir=temp_path)
        session_id = collector1.start_session(
            session_type="persistent", metadata={"instance": "first"}
        )

        # Record operations with first instance
        collector1.record_mcp_operation("find_symbol", session_id)
        collector1.record_mcp_operation("goto_definition", session_id)
        collector1.record_grep_operation(session_id)
        collector1.update_cache_stats(hits=5, misses=2, session_id=session_id)

        # Second collector instance - same storage directory
        collector2 = UnifiedMetricsCollector(storage_dir=temp_path)

        # Verify second instance can see existing session
        active_sessions = collector2.get_active_sessions()
        assert session_id in active_sessions

        # Verify all data is present
        session_data = active_sessions[session_id]
        assert session_data["session_type"] == "persistent"
        assert session_data["metadata"]["instance"] == "first"
        assert session_data["mcp_operations"]["find_symbol"] == 1
        assert session_data["mcp_operations"]["goto_definition"] == 1
        assert session_data["grep_operations"] == 1
        assert session_data["cache_hits"] == 5
        assert session_data["cache_misses"] == 2
        assert session_data["total_operations"] == 3

        # Second instance can continue recording to same session
        collector2.record_mcp_operation("find_references", session_id)
        collector2.record_grep_operation(session_id)

        # Verify updates are visible to both instances when reading
        updated_sessions = collector1.get_active_sessions()
        assert updated_sessions[session_id]["mcp_operations"]["find_references"] == 1
        assert updated_sessions[session_id]["grep_operations"] == 2
        assert updated_sessions[session_id]["total_operations"] == 5

        # End session with second instance
        final_metrics = collector2.end_session(session_id)
        assert final_metrics["statistics"]["mcp_operations_count"] == 3
        assert final_metrics["statistics"]["grep_operations_count"] == 2

        # Third instance verifies session is completed
        collector3 = UnifiedMetricsCollector(storage_dir=temp_path)
        active_sessions = collector3.get_active_sessions()
        assert session_id not in active_sessions  # Session is no longer active

        # Verify aggregated statistics were updated
        report = collector3.get_aggregated_report(days=1)
        assert report["summary"]["total_sessions"] >= 1
        assert report["summary"]["total_mcp_operations"] >= 3
        assert report["summary"]["total_grep_operations"] >= 2
