"""ReviewGate: build the human-review queue from prioritized findings."""

from typing import Dict, List, Optional

from backend.review.policy import build_audit_sample, requires_review


def _finding_item(issue: Dict, blocking: bool, reasons: List[str], kind: str) -> Dict:
    issue_id = issue.get("issue_id") or "unknown"
    return {
        "review_item_id": f"finding:{issue_id}",
        "kind": kind,
        "blocking": blocking,
        "reasons": reasons,
        "payload": issue,
    }


def build_review_queue(memory_snapshot: Dict, prioritized: List[Dict], decisions: List[Dict],
                       limit: Optional[int] = None) -> List[Dict]:
    queue: List[Dict] = []
    for issue in prioritized:
        reasons = requires_review(issue)
        queue.append(_finding_item(issue, bool(reasons), reasons, "finding" if reasons else "audit_finding"))
    if limit is None:
        for item in build_audit_sample(memory_snapshot, prioritized):
            queue.append(item)
    else:
        for item in build_audit_sample(memory_snapshot, prioritized, limit=limit):
            queue.append(item)
    return queue
