"""
validator.py - Stage 9: issue deduplication and validation (LLM).

Consolidates findings from Stages 5-8 (conflicts, full-set QAQC, code, and
constructability) into one clean, deduplicated canonical-issue list, dropping
unsupported or vague items. On failure it returns the input unchanged so no
findings are lost.
"""

from typing import Dict, List

from backend import config
from backend.pipeline._serialize import dumps
from backend.pipeline._stage import call_stage, collect_list, validate_issue
from backend.prompts import (
    DEDUP_VALIDATE_SYSTEM_PROMPT,
    DEDUP_VALIDATE_USER_INSTRUCTION,
)


def dedup_validate(all_issues: List[Dict]) -> List[Dict]:
    if not all_issues:
        return []
    parsed = call_stage(
        DEDUP_VALIDATE_SYSTEM_PROMPT,
        DEDUP_VALIDATE_USER_INSTRUCTION,
        subs={"issues": dumps(all_issues)},
        max_tokens=config.VALIDATE_MAX_TOKENS,
    )
    validated = collect_list(parsed, "issues", validate_issue)
    if not validated:
        # Model failed or returned nothing usable -- keep the raw findings.
        print(f"[Validate] dedup produced no list; keeping {len(all_issues)} raw issue(s)")
        return all_issues
    print(f"[Validate] {len(all_issues)} raw -> {len(validated)} consolidated issue(s)")
    return validated
