from typing import Any, Dict
from brox.model import CapabilityDiff


def emit_markdown_diff(diff: CapabilityDiff, policy_result: Dict[str, Any] = None) -> str:
    lines = []

    lines.append("## brox — Capability Diff (AI-BOM)")
    lines.append("")

    risk_level = diff.risk.level.upper()
    risk_emoji = {
        "LOW": "✅",
        "MEDIUM": "⚠️",
        "HIGH": "❌",
        "CRITICAL": "🔴",
    }.get(risk_level, "❓")

    lines.append(f"**Risk:** {risk_emoji} {risk_level}")

    if policy_result:
        decision = policy_result.get("decision", "pass")
        if decision == "block":
            triggered = policy_result.get("triggered_rules", [])
            blocking_rules = []
            for r in triggered:
                if r["action"] == "block":
                    blocking_rules.append(r)
            if blocking_rules:
                rule_id_list = []
                for r in blocking_rules:
                    rule_id_list.append(f"`{r['id']}`")
                rule_ids = ", ".join(rule_id_list)
                lines.append(f"**Decision:** Blocked by policy {rule_ids}")
        elif decision == "warn":
            lines.append("**Decision:** Warnings present")
        else:
            lines.append("**Decision:** Passed policy checks")
    lines.append("")

    if diff.assets_added or diff.assets_removed or diff.assets_changed:
        lines.append("### What changed (assets)")
        for asset in diff.assets_added:
            kind_label = format_asset_kind(asset.kind)
            lines.append(f"- + {kind_label}: `{asset.id}`")
        for asset in diff.assets_changed:
            kind_label = format_asset_kind(asset.kind)
            change = asset.change or "modified"
            lines.append(f"- ✏️ {kind_label} {change}: `{asset.id}`")
        for asset in diff.assets_removed:
            kind_label = format_asset_kind(asset.kind)
            lines.append(f"- - {kind_label}: `{asset.id}`")
        lines.append("")

    if diff.capabilities_added or diff.capabilities_widened or diff.capabilities_removed:
        lines.append("### Capability delta (Power changes)")

        if diff.capabilities_added:
            lines.append("**Added**")
            for cap in diff.capabilities_added:
                evidence = ", ".join(cap.evidence[:3])
                lines.append(f"- `{cap.capability}` scope=`{cap.scope}`")
                lines.append(f"  Evidence: `{evidence}`")

        if diff.capabilities_widened:
            lines.append("**Widened**")
            for cap in diff.capabilities_widened:
                evidence = ", ".join(cap.evidence[:3])
                lines.append(
                    f"- `{cap.capability}` from `{cap.from_scope}` → `{cap.to_scope}`"
                )
                lines.append(f"  Evidence: `{evidence}`")

        if diff.capabilities_removed:
            lines.append("**Removed**")
            for cap in diff.capabilities_removed:
                lines.append(f"- `{cap.capability}` scope=`{cap.scope}`")

        lines.append("")

    if diff.risk.reasons:
        lines.append("### Why this matters")
        for reason in diff.risk.reasons:
            lines.append(f"- {reason}")
        lines.append("")

    if policy_result and policy_result.get("decision") == "block":
        lines.append("### How to resolve")
        triggered_rules = policy_result.get("triggered_rules", [])
        blocking_rules = []
        for r in triggered_rules:
            if r["action"] == "block":
                blocking_rules.append(r)

        if blocking_rules:
            lines.append("This PR is blocked by the following policy rules:")
            lines.append("")
            for rule in blocking_rules:
                lines.append(f"**{rule['id']}**: {rule['message']}")
            lines.append("")
            lines.append("To resolve:")
            lines.append("- Review and address the policy violations")
            lines.append("- OR obtain security approval and add the `brox-approved` label")
        lines.append("")

    lines.append("---")
    lines.append("*Generated by [brox](https://github.com/yourusername/brox)*")

    return "\n".join(lines)


def format_asset_kind(kind: str) -> str:
    kind_labels = {
        "mcp_server": "MCP server",
        "mcp_tool": "MCP tool",
        "llm_provider": "LLM provider",
        "egress_sink": "Egress sink",
        "prompt": "Prompt",
        "agent_framework": "Agent framework",
    }
    return kind_labels.get(kind, kind)
