"""Check review formatting only. Does not establish bug correctness or safety."""
import re
import sys
from pathlib import Path

LINE = re.compile(r"- \[ \] \(severity: (high|medium|low)\) ([^\s:]+):([1-9][0-9]*) : (\S[^\r\n]*)")
RANK = {"high": 0, "medium": 1, "low": 2}
CLEAN = "No blocking issues found."


def validate(text):
    text = text.strip()
    if text == CLEAN:
        return
    lines = text.splitlines()
    if not 1 <= len(lines) <= 8:
        raise ValueError("Expected 1-8 findings or the exact no-issues response")
    previous = -1
    for number, line in enumerate(lines, 1):
        match = LINE.fullmatch(line)
        if match is None:
            raise ValueError(f"Line {number}: invalid checklist format")
        file_path = match[2]
        if file_path.startswith("/") or ".." in file_path.split("/") or "\\" in file_path:
            raise ValueError(f"Line {number}: expected a repository-relative POSIX path")
        rank = RANK[match[1]]
        if rank < previous:
            raise ValueError(f"Line {number}: severity must be high, medium, low")
        previous = rank


def main():
    if len(sys.argv) != 2:
        print("Usage: python3 check_review.py review.txt", file=sys.stderr)
        return 2
    try:
        validate(Path(sys.argv[1]).read_text(encoding="utf-8"))
    except (ValueError, OSError) as error:
        print(f"FAIL: {error}", file=sys.stderr)
        return 1
    print("PASS: format only; verify findings against the diff")
    return 0


if __name__ == "__main__":
    sys.exit(main())
