"""Human-first feature-analysis view model."""
from __future__ import annotations

from ..common import analysis_review_ids, evidence_index
from ..models import HumanReportView, VisualNode
from ..visualizations import flow_figure


_FLOW_KINDS = {"normal": "Normal path", "alternative": "Alternative path", "failure": "Failure path"}


def _flow_nodes(feature: dict) -> tuple[VisualNode, ...]:
    return tuple(
        VisualNode(
            id=row["id"],
            label=_FLOW_KINDS.get(row["kind"], row["kind"]),
            group=row["kind"],
            status="risk" if row["kind"] == "failure" else "stable",
            detail=" → ".join(step["action"] for step in row.get("steps", [])),
        )
        for row in feature.get("flows", [])
    )


def build_feature_analysis_view(data: dict) -> HumanReportView:
    feature = data["featureAnalysis"]
    figure = flow_figure(nodes=_flow_nodes(feature), edges=(), title="Feature behavior paths")
    context = {
        "humanSummary": data["humanSummary"],
        "feature": feature,
        "narrative": feature["userNarrative"],
        "flowFigure": figure,
        "analysisReviewIds": analysis_review_ids(data),
        "evidenceIndex": evidence_index(data),
    }
    return HumanReportView(
        task_type="feature-analysis",
        template_name="html/tasks/feature-analysis.template.html",
        context=context,
        figures=(figure,),
    )
