"""Log analysis module for processing structured log entries."""

from collections import defaultdict


def analyze_logs(entries: list[dict]) -> dict:
    """Analyze log entries and return frequency statistics.

    Returns frequency counts per level-source combination and a list of
    anomalous sources (those appearing with multiple severity levels).
    """
    freq = defaultdict(lambda: {"count": 0, "messages": []})
    for entry in entries:
        key = f"{entry['level']}:{entry['source']}"
        freq[key]["count"] += 1
        freq[key]["messages"].append(entry["message"])

    # Find anomalous sources and count how many cross-level conflicts each has
    anomalies = []
    for i, entry in enumerate(entries):
        conflicts = []
        for j, other in enumerate(entries):
            if (
                i != j
                and entry["source"] == other["source"]
                and entry["level"] != other["level"]
            ):
                conflicts.append(other["level"])
        if conflicts:
            anomalies.append(
                {
                    "source": entry["source"],
                    "level": entry["level"],
                    "index": i,
                    "conflict_count": len(conflicts),
                }
            )

    return {"frequencies": dict(freq), "anomalies": anomalies}
