"""Human-first implementation-direction comparison view."""
from __future__ import annotations

from ..common import evidence_index, scoped_anchor_map
from ..models import HumanReportView

# Record fields this template anchors as `id-<row id>` (see
# `HumanReportView.anchored_fields`); ids elsewhere land in the ledger.
ANCHORED_FIELDS = (
    "implementationOptionSelection.rankedOptions",
    "implementationOptionSelection.candidateAudit",
)
SCOPED_ANCHOR_FIELDS = (
    "implementationOptionSelection.rankedOptions.scopeCommitments",
    "implementationOptionSelection.rankedOptions.planningInvariants",
    "implementationOptionSelection.candidateAudit.scopeCommitments",
)


def _card_links(data: dict) -> dict[str, dict[str, str]]:
    links: dict[str, dict[str, str]] = {}
    for path in SCOPED_ANCHOR_FIELDS:
        for parent_id, children in scoped_anchor_map(data, path).items():
            links.setdefault(parent_id, {}).update(
                {child_id: f"#{anchor}" for child_id, anchor in children.items()}
            )
    return links


def build_implementation_option_selection_view(data: dict) -> HumanReportView:
    selection = data["implementationOptionSelection"]
    context = {
        "humanSummary": data["humanSummary"],
        "selection": selection,
        "directionSelection": (
            selection if selection["mode"] == "candidate-comparison" else None
        ),
        "narrative": selection["userNarrative"],
        # 기준별 가중치. 옵션 카드의 점수 표가 기준 이름 옆에 가중치를 같이
        # 보여야 가중 점수가 어떻게 나왔는지 읽힌다.
        "criteriaWeights": {
            criterion["criterion"]: criterion["weight"]
            for criterion in selection.get("evaluationCriteria") or []
            if isinstance(criterion, dict)
        },
        "recommendedOption": next(
            (
                option
                for option in selection["rankedOptions"]
                if option["id"] == selection["recommendedOptionId"]
            ),
            None,
        ),
        "evidenceIndex": evidence_index(data, ANCHORED_FIELDS, SCOPED_ANCHOR_FIELDS),
        # 카드별 링크 맵. 방향마다 `IC-001` 이 다시 시작하므로 그 카드 안의
        # 인용은 그 카드의 행으로만 간다.
        "cardLinks": _card_links(data),
    }
    return HumanReportView(
        task_type="implementation-option-selection",
        template_name="html/tasks/implementation-option-selection.template.html",
        context=context,
        figures=(),
        anchored_fields=ANCHORED_FIELDS,
        scoped_anchor_fields=SCOPED_ANCHOR_FIELDS,
    )
