"""
qaqc_review.py - Stage 6: senior architect full-set QAQC review (LLM).

One whole-set reasoning pass that surfaces QAQC issues BEYOND the direct
cross-discipline conflicts already found in Stage 5 -- missing sheets/schedules/
details, incomplete information, bid/permit-readiness gaps. Text-based over the
already-extracted assertions, clusters, and conflicts; emits the canonical issue
schema. Returns [] on failure.
"""

from typing import Dict, List

from backend import config
from backend.pipeline._serialize import dumps, slim_clusters, slim_sheets
from backend.pipeline._stage import call_stage, collect_list, validate_issue
from backend.prompts import SENIOR_QAQC_SYSTEM_PROMPT, SENIOR_QAQC_USER_INSTRUCTION


def senior_review(sheets: List[Dict], clusters: List[Dict],
                  conflicts: List[Dict], sheet_index: Dict) -> List[Dict]:
    parsed = call_stage(
        SENIOR_QAQC_SYSTEM_PROMPT,
        SENIOR_QAQC_USER_INSTRUCTION,
        subs={
            "sheet_index": dumps(sheet_index or {}),
            "assertions": dumps(slim_sheets(sheets)),
            "clusters": dumps(slim_clusters(clusters)),
            "conflicts": dumps(conflicts),
        },
        max_tokens=config.QAQC_MAX_TOKENS,
    )
    issues = collect_list(parsed, "issues", lambda c: validate_issue(c, "qaqc"))
    print(f"[QAQC] {len(issues)} full-set QAQC issue(s)")
    return issues
