"""Human-first release-handoff view model."""
from __future__ import annotations

from urllib.parse import urlparse

from ..common import evidence_index
from ..models import HumanReportView, VisualNode
from ..visualizations import timeline_figure


def _safe_http_url(value: str) -> str:
    parsed = urlparse(value)
    return value if parsed.scheme in {"http", "https"} and parsed.netloc else ""


def _timeline_nodes(handoff: dict) -> tuple[VisualNode, ...]:
    selection = handoff["userSelections"]["h1"]
    branch = handoff["featureBranchState"]["branchName"]
    conflict = handoff["mergeConflictProbe"]["kind"]
    pr = handoff["pullRequestOutcome"]["kind"]
    return (
        VisualNode("selection", selection, "handoff", "completed", "User-selected handoff"),
        VisualNode("branch", branch, "handoff", "completed", "Feature branch state"),
        VisualNode("conflict", conflict, "handoff", conflict, "Merge conflict probe"),
        VisualNode("pull-request", pr, "handoff", pr, "Pull request outcome"),
    )


def build_release_handoff_view(data: dict) -> HumanReportView:
    handoff = data["releaseHandoff"]
    figure = timeline_figure(
        events=_timeline_nodes(handoff), title="Release handoff timeline"
    )
    context = {
        "humanSummary": data["humanSummary"],
        "handoff": handoff,
        "narrative": handoff["userNarrative"],
        "handoffFigure": figure,
        "prUrl": _safe_http_url(handoff["pullRequestOutcome"].get("url", "")),
        "evidenceIndex": evidence_index(data),
    }
    return HumanReportView(
        "release-handoff",
        "html/tasks/release-handoff.template.html",
        context,
        (figure,),
    )
