﻿from __future__ import annotations

from typing import Any, Dict
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse

import httpx

from app.config import settings

LINE_REPLY_API = "https://api.line.me/v2/bot/message/reply"


def _build_direct_voter_url(join_url: str, room_id: str) -> str:
    """Convert /join?token=xxx to /voter?token=xxx for direct mobile entry."""
    try:
        parsed = urlparse(join_url)
        token = (parse_qs(parsed.query).get("token") or [""])[0].strip()
        if not token:
            return join_url
        new_query = urlencode({"token": token, "room_id": room_id})
        return urlunparse(parsed._replace(path="/voter", query=new_query))
    except Exception:
        return join_url


async def reply_join_link(*, reply_token: str, join_url: str, room_id: str) -> Dict[str, Any]:
    if not settings.line_channel_access_token:
        return {
            "ok": False,
            "skipped": True,
            "reason": "line_channel_access_token_not_configured",
            "join_url": join_url,
        }

    payload = {
        "replyToken": reply_token,
        "messages": [
            {
                "type": "template",
                "altText": "進入互動投票",
                "template": {
                    "type": "buttons",
                    "title": "進入互動投票",
                    "text": f"點擊下方按鈕，加入場次 {room_id}",
                    "actions": [
                        {
                            "type": "uri",
                            "label": "進入互動",
                            "uri": _build_direct_voter_url(join_url, room_id),
                        }
                    ],
                },
            }
        ],
    }
    headers = {
        "Authorization": f"Bearer {settings.line_channel_access_token}",
        "Content-Type": "application/json",
    }

    async with httpx.AsyncClient(timeout=15.0) as client:
        response = await client.post(LINE_REPLY_API, json=payload, headers=headers)
        if response.is_success:
            return {"ok": True, "status_code": response.status_code}
        return {
            "ok": False,
            "status_code": response.status_code,
            "body": response.text,
        }
