# -*- coding: utf-8 -*-
"""host/protocol.py

yjm_win2rtc WebSocket JSON 메시지 타입 상수 모음.

원칙:
- 화면 프레임은 binary JPEG 또는 향후 tile binary/json 혼합으로 보낸다.
- 제어/클립보드/로그/오류/파일 메타는 JSON text message로 보낸다.
- v2 호환을 위해 LEGACY_MSG_CLIPBOARD="clipboard", WS_TYPE_CONTROL="control"도 남긴다.
"""

from __future__ import annotations

from typing import Any

# Clipboard
MSG_CLIPBOARD_SET = "clipboard_set"      # viewer -> host: {type, text}
MSG_CLIPBOARD_GET = "clipboard_get"      # viewer -> host: {type}
MSG_CLIPBOARD_DATA = "clipboard_data"    # host -> viewer: {type, text, length, preview}

# Mouse
MSG_MOUSE_MOVE = "mouse_move"
MSG_MOUSE_DOWN = "mouse_down"
MSG_MOUSE_UP = "mouse_up"
MSG_MOUSE_CLICK = "mouse_click"
MSG_MOUSE_WHEEL = "mouse_wheel"

# Keyboard / text
MSG_KEY_DOWN = "key_down"
MSG_KEY_UP = "key_up"
MSG_TEXT_INPUT = "text_input"

# File transfer. 현재 HTTP upload가 동작 중이고, 아래 타입은 다음 WebSocket chunk 전송용 고정 규칙이다.
MSG_FILE_START = "file_start"
MSG_FILE_CHUNK = "file_chunk"
MSG_FILE_END = "file_end"

# Screen
MSG_SCREEN_FULL = "screen_full"
MSG_SCREEN_TILE = "screen_tile"
MSG_SCREEN_SIZE = "screen_size"

# Host/viewer option control
MSG_HOST_OPTION_SET = "host_option_set"  # viewer -> host: {type, name, value}
MSG_HOST_OPTION_ACK = "host_option_ack"  # host -> viewer: {type, name, value, ok}

# Common
MSG_ERROR = "error"
MSG_LOG = "log"
MSG_NOTIFY = "notify"  # v2 UI toast/file progress 호환용

# v2 compatibility group types
LEGACY_MSG_CLIPBOARD = "clipboard"
WS_TYPE_CONTROL = "control"

ALL_MESSAGE_TYPES = {
    MSG_CLIPBOARD_SET,
    MSG_CLIPBOARD_GET,
    MSG_CLIPBOARD_DATA,
    MSG_MOUSE_MOVE,
    MSG_MOUSE_DOWN,
    MSG_MOUSE_UP,
    MSG_MOUSE_CLICK,
    MSG_MOUSE_WHEEL,
    MSG_KEY_DOWN,
    MSG_KEY_UP,
    MSG_TEXT_INPUT,
    MSG_FILE_START,
    MSG_FILE_CHUNK,
    MSG_FILE_END,
    MSG_SCREEN_FULL,
    MSG_SCREEN_TILE,
    MSG_SCREEN_SIZE,
    MSG_HOST_OPTION_SET,
    MSG_HOST_OPTION_ACK,
    MSG_ERROR,
    MSG_LOG,
    MSG_NOTIFY,
    LEGACY_MSG_CLIPBOARD,
    WS_TYPE_CONTROL,
}


def make_msg(message_type: str, **fields: Any) -> dict[str, Any]:
    """표준 JSON 메시지 dict 생성."""
    payload = {"type": str(message_type)}
    payload.update(fields)
    return payload


def get_msg_type(payload: object) -> str:
    if not isinstance(payload, dict):
        return ""
    value = payload.get("type", "")
    return str(value) if value is not None else ""
