"""Agrega y deduplica entidades + relaciones de N resultados de extraccion por chunk."""

from __future__ import annotations

from collections import Counter


def aggregate_extraction_results(extract_results: list[dict]) -> dict:
    """Aggregate entities + relations from multiple chunk-level extraction results.

    Deduplicates entities by (type, name_lowercased) and counts occurrences.
    Deduplicates relations by (head, rel_type, tail) and counts occurrences.

    Each input result is expected to have shape:
        {"entities": {type: [name, ...]}, "relation_extraction": {rel_type: [(head, tail), ...]}}
    This is the output format of extract_graph_gliner2.

    Args:
        extract_results: List of per-chunk extraction dicts. May be empty.
                         Missing keys ("entities", "relation_extraction") are tolerated.

    Returns:
        {
          "entities": dict[(type, name_lower)] -> {"type": str, "name": str, "count": int},
          "relations": Counter mapping (head, rel_type, tail) -> count
        }
    """
    all_ents: dict[tuple[str, str], dict] = {}
    all_rels: Counter = Counter()

    for r in extract_results:
        for typ, names in (r.get("entities") or {}).items():
            for n in names:
                key = (typ, (n or "").strip().lower())
                if not key[1]:
                    continue
                if key not in all_ents:
                    all_ents[key] = {"type": typ, "name": n.strip(), "count": 0}
                all_ents[key]["count"] += 1

        for rt, pairs in (r.get("relation_extraction") or {}).items():
            for h, t in pairs:
                all_rels[(h.strip(), rt, t.strip())] += 1

    return {"entities": all_ents, "relations": all_rels}
