from __future__ import annotations

from glacier.analysis.anomaly import Severity
from glacier.analysis.cross_ref import Investigation


def render_digest(investigation: Investigation) -> str:
    lines: list[str] = []
    lines.append(f"# {investigation.name}")
    lines.append(f"\n{investigation.description}")

    by_sev = investigation.by_severity()
    total = len(investigation.findings)
    lines.append("\n## Summary")
    lines.append(f"- **{total}** findings across **{len(investigation.sources_used)}** data sources")

    for sev in reversed(list(Severity)):
        count = len(by_sev[sev])
        if count:
            lines.append(f"- {sev.value.upper()}: {count}")

    top = investigation.top_entities(10)
    if top:
        lines.append("\n## Top Entities")
        for entity, score, worst_sev in top:
            corr = investigation.corroboration_score(entity)
            lines.append(f"- **{entity}** — score={score}, worst={worst_sev.value}, corroboration={corr:.2f}")

    lines.append("\n## Detailed Findings")
    for sev in reversed(list(Severity)):
        findings = by_sev[sev]
        if not findings:
            continue
        lines.append(f"\n### {sev.value.upper()}")
        for f in findings:
            lines.append(f"- [{f.anomaly_type.value}] **{f.entity}**: {f.description}")
            if f.evidence:
                lines.append(f"  - Evidence: {', '.join(f.evidence)}")
            if f.data_sources:
                lines.append(f"  - Sources: {', '.join(f.data_sources)}")

    lines.append("\n## Data Sources Used")
    for src in investigation.sources_used:
        lines.append(f"- {src}")

    lines.append("\n---")
    lines.append(f"— Glacier\U0001f9ca: {investigation.name}|{','.join(investigation.sources_used)}")

    return "\n".join(lines)
