"""Post adversarial review results as a PR comment via gh CLI.

Stdlib-only. Formats review JSON into a readable markdown comment.
"""

from __future__ import annotations

import argparse
import json
import subprocess
import sys

SEVERITY_ICONS = {
    "info": "\u2139\ufe0f",  # info
    "warning": "\u26a0\ufe0f",  # warning
    "error": "\u274c",  # error
    "critical": "\U0001f6a8",  # critical
}

CATEGORY_ICONS = {
    "security": "\U0001f512",  # lock
    "correctness": "\U0001f3af",  # bullseye
    "performance": "\u26a1",  # lightning
    "style": "\U0001f3a8",  # palette
    "causal_reasoning": "\U0001f9ec",  # dna
}


def format_review(review: dict) -> str:
    """Format review JSON into a markdown comment."""
    lines = []
    lines.append("## \U0001f916 Adversarial Code Review\n")

    summary = review.get("summary", "No summary available.")
    risk = review.get("risk_level", "unknown")
    approval = review.get("approval", "comment")

    lines.append(f"**Summary:** {summary}")
    lines.append(f"**Risk Level:** {risk}")
    lines.append(f"**Recommendation:** {approval}\n")

    findings = review.get("findings", [])
    if findings:
        lines.append("### Findings\n")
        for i, finding in enumerate(findings, 1):
            severity = finding.get("severity", "info")
            category = finding.get("category", "style")
            sev_icon = SEVERITY_ICONS.get(severity, "\u2139\ufe0f")
            cat_icon = CATEGORY_ICONS.get(category, "\U0001f50d")
            title = finding.get("title", "Untitled")
            file_path = finding.get("file", "unknown")
            line = finding.get("line", "?")
            detail = finding.get("detail", "")
            suggestion = finding.get("suggestion", "")

            lines.append(f"**{i}. {sev_icon} {cat_icon} {title}**")
            lines.append(f"  `{file_path}:{line}`")
            if detail:
                lines.append(f"  {detail}")
            if suggestion:
                lines.append(f"  \U0001f4a1 *{suggestion}*")
            lines.append("")
    else:
        lines.append("No issues found. Clean diff.\n")

    lines.append("---")
    lines.append("*Reviewed by adversarial AI (segregation of duty).*")
    lines.append("*Final approval: Operator only.*")

    return "\n".join(lines)


def main() -> None:
    parser = argparse.ArgumentParser(description="Post review comment to PR")
    parser.add_argument("--review", required=True, help="Path to review JSON")
    parser.add_argument("--pr", required=True, help="PR number")
    args = parser.parse_args()

    with open(args.review) as f:
        review = json.load(f)

    comment_body = format_review(review)
    print("Posting review comment...")
    print(comment_body)

    result = subprocess.run(
        ["gh", "pr", "comment", args.pr, "--body", comment_body],
        capture_output=True,
        text=True,
    )

    if result.returncode != 0:
        print(f"Failed to post comment: {result.stderr}", file=sys.stderr)
        sys.exit(1)

    print("Review comment posted successfully.")


if __name__ == "__main__":
    main()
