"""Combined analyzer that fuses analyze_traces and match_traces to avoid duplicate trace loading."""
from pathlib import Path
from typing import Any
from .analyzer import analyze_traces
from .graph_matcher import load_cuda_graphs, match_graph_pairs
from .loader import load_trace
def analyze_and_match_combined(
    trace1_path: str | Path,
    trace2_path: str | Path,
    phase_filter: str = "all",
    max_stacks: int = 3,
    min_graph_size: int = 300,
) -> tuple[dict[str, Any], dict[str, Any]]:
    """Combined analysis that loads traces once for both analyze_traces and match_traces.
    This is an experimental optimization that avoids loading traces twice.
    Args:
        trace1_path: Path to first trace file
        trace2_path: Path to second trace file
        phase_filter: Phase filter ('all', 'prefill', 'decode')
        max_stacks: Maximum stack traces to include
        min_graph_size: Minimum CUDA graph size threshold
    Returns:
        Tuple of (analyze_result, match_result)
    """
    trace1_path = Path(trace1_path)
    trace2_path = Path(trace2_path)

    # analyze_traces uses load_trace() which returns: (platform, gpu, device, df, patterns, layers)
    # match_traces uses load_cuda_graphs() which loads JSON and groups by correlation
    # Strategy 1: Run analyze_traces first (it loads traces internally)
    # Then run match_traces (it will reload - unavoidable without refactoring load_cuda_graphs)
    analyze_result = analyze_traces(trace1_path, trace2_path, phase_filter=phase_filter, max_stacks=max_stacks)

    amd_platform, amd_graphs = load_cuda_graphs(trace1_path, min_kernels=1)
    nv_platform, nv_graphs = load_cuda_graphs(trace2_path, min_kernels=1)
    # Perform graph matching (this is the matching algorithm, without loading)
    match_result = match_graph_pairs(
        amd_platform, amd_graphs,
        nv_platform, nv_graphs,
        min_graph_size=min_graph_size
    )
    return analyze_result, match_result
