"""Generiert eine Visuals-Übersicht aus den Metadaten.

Erstellt eine Zusammenfassung der Berichtsseiten, Visualisierungstypen
und verwendeten Felder. Sprachabhängig (de/en).
"""
from __future__ import annotations

from collections import Counter, defaultdict

from core.label_i18n import visual_type_label
from core.models import ReportMetadata

_T: dict[str, dict[str, str]] = {
    "de": {
        "empty": "*Keine Visualisierungsinformationen verfügbar (bei PBIP-Projekten "
                 "automatisch extrahiert, bei Service-Verbindung Report-ID erforderlich).*",
        "pages_heading": "#### Berichtsseiten",
        "pages_summary": "Der Bericht enthält **{pages} Seite(n)** mit insgesamt "
                         "**{visuals} Visualisierungen**.",
        "th_pages": "| Seite | Anzahl Visuals | Visualtypen |",
        "sep_pages": "|-------|---------------|-------------|",
        "types_heading": "#### Verwendete Visualtypen",
        "th_types": "| Visualtyp | Anzahl |",
        "sep_types": "|-----------|--------|",
        "slicers_heading": "#### Datenschnitte / Filter",
        "th_slicers": "| Seite | Felder |",
        "sep_slicers": "|-------|--------|",
        "detail_heading": "#### Visualisierungen im Detail",
        "th_detail": "| Seite | Typ | ID | Anzeigename | Felder |",
        "sep_detail": "|-------|-----|----|-------------|--------|",
        "unknown_page": "Unbekannte Seite",
    },
    "en": {
        "empty": "*No visualization information available (extracted automatically for "
                 "PBIP projects; a Report ID is required for service connections).*",
        "pages_heading": "#### Report Pages",
        "pages_summary": "The report contains **{pages} page(s)** with a total of "
                         "**{visuals} visualizations**.",
        "th_pages": "| Page | # Visuals | Visual types |",
        "sep_pages": "|------|-----------|--------------|",
        "types_heading": "#### Visual Types Used",
        "th_types": "| Visual type | Count |",
        "sep_types": "|-------------|-------|",
        "slicers_heading": "#### Slicers / Filters",
        "th_slicers": "| Page | Fields |",
        "sep_slicers": "|------|--------|",
        "detail_heading": "#### Visualizations in Detail",
        "th_detail": "| Page | Type | ID | Display name | Fields |",
        "sep_detail": "|------|------|----|--------------|--------|",
        "unknown_page": "Unknown page",
    },
}


def generate_visuals_summary(metadata: ReportMetadata, language: str = "de") -> str:
    """Erzeugt eine Markdown-Zusammenfassung der Visuals und Seiten."""
    t = _T.get(language, _T["de"])

    if not metadata.visuals:
        return t["empty"]

    sections: list[str] = []

    # 1) Seiten-Übersicht
    pages: dict[str, list] = defaultdict(list)
    for vis in metadata.visuals:
        pages[vis.page_name or t["unknown_page"]].append(vis)

    sections.append(t["pages_heading"] + "\n")
    sections.append(
        t["pages_summary"].format(pages=len(pages), visuals=len(metadata.visuals)) + "\n"
    )

    sections.append(t["th_pages"])
    sections.append(t["sep_pages"])
    for page_name, visuals in pages.items():
        count = len(visuals)
        type_counts = Counter(
            visual_type_label(v.visual_type, language) for v in visuals
        )
        types_str = ", ".join(
            f"{name} ({c})" for name, c in type_counts.most_common(5)
        )
        sections.append(f"| {page_name} | {count} | {types_str} |")
    sections.append("")

    # 2) Visualtypen-Übersicht
    all_types = Counter(
        visual_type_label(v.visual_type, language) for v in metadata.visuals
    )
    sections.append(t["types_heading"] + "\n")
    sections.append(t["th_types"])
    sections.append(t["sep_types"])
    for vtype, count in all_types.most_common():
        sections.append(f"| {vtype} | {count} |")
    sections.append("")

    # 3) Datenschnitte (Slicer/Filter)
    slicers = [v for v in metadata.visuals if v.visual_type == "slicer"]
    if slicers:
        sections.append(t["slicers_heading"] + "\n")
        sections.append(t["th_slicers"])
        sections.append(t["sep_slicers"])
        for s in slicers:
            fields = ", ".join(s.fields) if s.fields else "–"
            sections.append(f"| {s.page_name} | {fields} |")
        sections.append("")

    # 4) Detail-Tabelle: alle Visuals mit Seite, Typ, ID, Anzeigename und Feldern
    sections.append(t["detail_heading"] + "\n")
    sections.append(t["th_detail"])
    sections.append(t["sep_detail"])
    for vis in metadata.visuals:
        vtype = visual_type_label(vis.visual_type, language)
        vis_id = vis.title or "–"
        display_name = vis.display_name or vtype
        fields = ", ".join(vis.fields) if vis.fields else "–"
        if len(fields) > 80:
            fields = fields[:77] + "…"
        sections.append(f"| {vis.page_name} | {vtype} | {vis_id} | {display_name} | {fields} |")
    sections.append("")

    return "\n".join(sections)
