"""Attach TikTok's request signature.

msToken is borrowed from the user's session cookies and appended to the query, which
some read endpoints accept. X-Bogus / X-Gnarly is TikTok's rotating anti-automation
signature, generated by obfuscated browser JS; we deliberately do NOT reproduce it
here, because a stale or wrong signature is worse than none and TikTok changes it on a
whim. When a call comes back signature-rejected, the shim says so and points at the
browser agent, which signs naturally by being a real browser. This is the TikTok analog
of Reddit's token-harvest and X's queryIds: the one isolated, not-live-proven piece.
"""

import urllib.parse
from typing import Any, Dict

from backend.apps.social_shims.session_source import cookie_value
from backend.apps.tiktok_mcp_shim.tiktok_endpoints import DEVICE_PARAMS, DOMAIN, MSTOKEN_COOKIE


def signed_query(params: Dict[str, Any]) -> str:
    """Build the query string with device params + the borrowed msToken."""
    q = dict(DEVICE_PARAMS)
    q.update({k: v for k, v in params.items() if v is not None})
    ms = cookie_value(DOMAIN, MSTOKEN_COOKIE)
    if ms:
        q["msToken"] = ms
    # X-Bogus / X-Gnarly intentionally omitted; see module docstring.
    return urllib.parse.urlencode(q)
