#!/usr/bin/env python3
"""Review one task's diff and print the verdict. Merge nothing.

    bin/review AUD-164            # review and print
    bin/review AUD-164 --post     # also write the verdict on the task

This is the same review `bin/merge` runs, on its own, so a person can look
before the merge is attempted. Exit 0 means nothing blocking was found; exit 5
means the review refused; exit 7 means there is no worktree to look at.
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib"))
import harness as h  # noqa: E402


def main():
    args = [a for a in sys.argv[1:] if not a.startswith("--")]
    post = "--post" in sys.argv
    if len(args) != 1:
        h.say("usage: bin/review <task> [--post]")
        return 2

    issue = h.find_issue(args[0])
    ref = issue["identifier"]
    worktree, branch, base = h.worktree_of(issue)

    h.say("%s %s" % (ref, issue["title"]))
    h.say("  worktree %s" % worktree)
    h.say("  range    %s...HEAD (%s)" % (base, branch))

    report = h.ocr_review(worktree, base, "HEAD")
    status = report.get("status")
    reviewed = (report.get("summary") or {}).get("files_reviewed", 0)
    comments = report.get("comments") or []

    if status == "skipped" and reviewed == 0:
        h.say("  nothing reviewable in the change (0 files)")
        if post:
            h.verdict(issue, "## Review: nothing to review\n\nocr selected 0 files "
                      "from the change, so nothing was checked.")
        return 0
    if status != "complete":
        h.say("  review could not complete: %s" % (report.get("message") or status))
        if post:
            h.verdict(issue, "## Review could not run\n\nocr returned `%s` — %s"
                      % (status, report.get("message") or "no reason given"))
        return 5

    blocking = h.blocking_findings(report)
    for c in comments:
        marker = "BLOCKS" if c in blocking else "note  "
        h.say("  %s %s" % (marker, h.describe(c)))

    verdict = ("%d comment(s); %d blocking" % (len(comments), len(blocking)))
    h.say("  %s" % verdict)

    if post:
        body = "## Review\n\n%s" % (verdict)
        if blocking:
            body += "\n\nBlocking:\n" + "\n".join(h.describe(c) for c in blocking)
        h.verdict(issue, body)

    return 5 if blocking else 0


if __name__ == "__main__":
    h.main_guard(main)
