"""Parse hihaho interaction JSON to extract branch decision schedules.

Each branch group is a pair of hotspots sharing the same (start_time, end_time)
plus a jump_to that fires at end_time as the default fallback.
"""

from typing import Any


def seconds_to_position(seconds: float) -> str:
    h = int(seconds // 3600)
    m = int((seconds % 3600) // 60)
    s = seconds % 60
    return f"{h:02d}:{m:02d}:{s:05.2f}"


def _hotspot_left(hotspot: dict) -> float:
    left_str = hotspot.get("style", {}).get("left", "0%").replace("%", "")
    try:
        return float(left_str)
    except (ValueError, TypeError):
        return 0.0


def parse_branches(interactions: list[dict[str, Any]]) -> list[dict[str, Any]]:
    """Return a list of branch decision points, each with timing and hotspot options.

    Only groups with 2+ hotspots are considered real branch choices
    (single-hotspot groups are typically "go back" buttons).
    """
    hotspot_groups: dict[tuple[float, float], list[dict]] = {}
    jump_tos: dict[float, dict] = {}

    for item in interactions:
        itype = item.get("type", "")
        action = item.get("action") or {}
        if action.get("type") != "jump":
            continue

        if itype == "hotspot":
            st = item.get("start_time")
            et = item.get("end_time")
            if st is not None and et is not None:
                key = (float(st), float(et))
                hotspot_groups.setdefault(key, []).append(item)

        elif itype == "jump_to":
            st = item.get("start_time")
            if st is not None:
                jump_tos[float(st)] = item

    branches: list[dict[str, Any]] = []
    for (start_time, end_time), hotspots in sorted(hotspot_groups.items()):
        if len(hotspots) < 2:
            continue

        default_jt = jump_tos.get(end_time)
        default_jump_time = (
            float(default_jt["action"]["time"]) if default_jt else None
        )

        sorted_hotspots = sorted(hotspots, key=_hotspot_left)

        options = []
        for i, h in enumerate(sorted_hotspots):
            jt = float(h["action"]["time"])
            options.append({
                "index": i,
                "jump_time": jt,
                "position": seconds_to_position(jt),
                "left": h.get("style", {}).get("left", ""),
                "is_default": jt == default_jump_time,
            })

        branches.append({
            "branch_index": len(branches),
            "start_time": start_time,
            "end_time": end_time,
            "duration_seconds": end_time - start_time,
            "default_jump_time": default_jump_time,
            "options": options,
        })

    return branches
