"""Markdown report builder for a completed 5 Whys investigation."""

from __future__ import annotations


def build_report(
    investigation_id: str,
    phenomenon: str,
    domain_context: str,
    nodes: list[dict],
    timestamp: str,
) -> str:
    """Assemble and return the full investigation report as a markdown string."""
    tree_lines = []
    for node in nodes:
        indent = "  " * (node["depth"] - 1)
        status = "OK" if node["gemba_result"] == "OK" else "NOK"
        tree_lines.append(f"{indent}- [{node['branch_path']}] **{status}** {node['hypothesis']}")
        if node["gemba_notes"]:
            tree_lines.append(f"{indent}  *Gemba notes:* {node['gemba_notes']}")
        if node["countermeasure"]:
            tree_lines.append(f"{indent}  *Countermeasure:* {node['countermeasure']}")

    root_causes = [n for n in nodes if n.get("is_root_cause") or n.get("countermeasure")]
    countermeasure_lines = [
        f"- **Root cause [{rc['branch_path']}]:** {rc['hypothesis']}\n"
        f"  **Countermeasure:** {rc['countermeasure']}"
        for rc in root_causes
        if rc.get("countermeasure")
    ]

    return (
        f"# 5 Whys Investigation Report\n\n"
        f"**Investigation ID:** {investigation_id}  \n"
        f"**Date:** {timestamp}  \n"
        f"**Domain:** {domain_context}  \n\n"
        f"---\n\n"
        f"## Phenomenon\n\n"
        f"> {phenomenon}\n\n"
        f"---\n\n"
        f"## Why Tree\n\n"
        + "\n".join(tree_lines)
        + "\n\n---\n\n"
        f"## Root Causes & Countermeasures\n\n"
        + ("\n\n".join(countermeasure_lines) if countermeasure_lines else "_No root causes confirmed._")
        + f"\n\n---\n\n*Generated by 5 Whys Agent — {timestamp}*\n"
    )
