# crash tested, mother approved
"""
Formats raw ADP API response into a concise, Claude-friendly text summary.
Claude doesn't need 20K of raw JSON -- it needs structured findings it can reason about.
"""


def format_analysis(data: dict) -> str:
    """Format a Tier2AnalysisReport dict into structured text for Claude."""
    base_report = data.get("base_report", {})
    analyses = data.get("analyses", [])
    doc_name = base_report.get("document_name", "Unknown")

    total_citations = base_report.get("total_citations", 0)
    total_analyzed = data.get("total_analyzed", 0)
    total_supporting = data.get("total_supporting", 0)
    total_not_supporting = data.get("total_not_supporting", 0)
    total_unclear = data.get("total_unclear", 0)
    total_auto_escalated = data.get("total_auto_escalated", 0)

    # Verification stats
    verified_count = base_report.get("verified_count", 0)
    unverifiable_count = base_report.get("unverifiable_count", 0)
    flagged_count = base_report.get("flagged_for_review_count", 0)

    lines = []
    lines.append("ADP DEEP ANALYSIS RESULTS")
    lines.append(f"Document: {doc_name}")
    lines.append(f"Citations found: {total_citations}")
    lines.append(f"Analyzed: {total_analyzed}")
    lines.append("")

    # Summary
    lines.append("SUMMARY")
    lines.append(f"- {total_supporting} citations SUPPORT the argument")
    lines.append(f"- {total_not_supporting} citations DO NOT SUPPORT the argument")
    lines.append(f"- {total_unclear} citations UNCLEAR")
    if total_auto_escalated > 0:
        lines.append(f"- {total_auto_escalated} citations AUTO-ESCALATED for expert review")
    lines.append("")

    # Flagged issues (splits, low confidence, opposes)
    flagged = []
    for a in analyses:
        is_flagged = (
            a.get("auto_escalated")
            or a.get("agreement_level") == "split"
            or a.get("consensus_supports") is False
            or (a.get("confidence", 1.0) < 0.5)
        )
        if is_flagged:
            flagged.append(a)

    if flagged:
        lines.append(f"FLAGGED ISSUES ({len(flagged)}):")
        lines.append("")

        for i, f in enumerate(flagged, 1):
            citation = f.get("citation_text", "Unknown")
            agreement = f.get("agreement_level", "unknown")
            confidence = f.get("confidence", 0)
            supports = f.get("consensus_supports")

            if supports is True:
                verdict = "SUPPORTS"
            elif supports is False:
                verdict = "DOES NOT SUPPORT"
            else:
                verdict = "UNCLEAR"

            lines.append(f"{i}. {citation} - {verdict} ({agreement}, {confidence:.0%} confidence)")

            # Show individual LLM assessments for flagged items
            for assessment in f.get("assessments", []):
                if assessment.get("error"):
                    continue
                provider = assessment.get("provider", "unknown")
                model = assessment.get("model", "unknown")
                a_supports = assessment.get("supports_argument")
                a_conf = assessment.get("confidence", 0)
                a_reasoning = assessment.get("reasoning", "")

                if a_supports is True:
                    a_verdict = "SUPPORTS"
                elif a_supports is False:
                    a_verdict = "OPPOSES"
                else:
                    a_verdict = "UNCLEAR"

                # Truncate reasoning to keep output manageable
                if len(a_reasoning) > 200:
                    a_reasoning = a_reasoning[:197] + "..."
                lines.append(f"   {provider} ({model}): {a_verdict} ({a_conf:.0%}) - \"{a_reasoning}\"")

            if f.get("auto_escalated"):
                lines.append("   >> Expert review recommended")
            lines.append("")
    else:
        lines.append("NO FLAGGED ISSUES")
        lines.append("")

    # All citations
    lines.append("ALL CITATIONS:")
    for i, a in enumerate(analyses, 1):
        citation = a.get("citation_text", "Unknown")
        agreement = a.get("agreement_level", "unknown")
        confidence = a.get("confidence", 0)
        supports = a.get("consensus_supports")
        ctype = a.get("citation_type", "")

        if supports is True:
            verdict = "SUPPORTS"
        elif supports is False:
            verdict = "DOES NOT SUPPORT"
        else:
            verdict = "UNCLEAR"

        type_label = f" [{ctype}]" if ctype else ""
        lines.append(f"{i}. [{verdict}]{type_label} {citation} - {agreement} {confidence:.0%}")

    lines.append("")

    # Verification summary
    lines.append(f"VERIFICATION: {verified_count} verified, {unverifiable_count} not found, {flagged_count} needs review")

    return "\n".join(lines)
