"""hihaho API bridge (MVP stub + optional server-side proxy).

Assumption A1: actual branch/jump APIs depend on hihaho product documentation.
Use HIHaho Client only when HIHAHO_API_BASE and HIHAHO_API_KEY are set.
"""

from typing import Any, Dict, Optional

import httpx

from app.config import settings


async def notify_branch_result(
    *,
    film_session_id: str,
    branch_key: str,
    metadata: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """POST to hihaho proxy endpoint if configured; otherwise return a safe fallback payload."""
    base = (settings.hihaho_api_base or "").rstrip("/")
    if not base or not settings.hihaho_api_key:
        return {
            "ok": False,
            "skipped": True,
            "reason": "hihaho_api_not_configured",
            "film_session_id": film_session_id,
            "branch_key": branch_key,
            "metadata": metadata or {},
        }

    branch_path = settings.hihaho_branch_path or "/interactive/resolution"
    if not branch_path.startswith("/"):
        branch_path = "/" + branch_path
    url = f"{base}{branch_path}"
    headers = {"Authorization": f"Bearer {settings.hihaho_api_key}"}
    payload = {"filmSessionId": film_session_id, "branchKey": branch_key, **(metadata or {})}

    async with httpx.AsyncClient(timeout=15.0) as client:
        response = await client.post(url, json=payload, headers=headers)
        response.raise_for_status()
        try:
            return {"ok": True, "endpoint": branch_path, "data": response.json()}
        except Exception:
            return {"ok": True, "endpoint": branch_path, "data": response.text}
