"""Selectors and URL builders for Alibaba inquiry pages."""

from __future__ import annotations

import json
from urllib.parse import quote

DEFAULT_LIST_URL = "https://message.alibaba.com/message/default.htm#feedback/all"


def _build_search_url(page_num: int, payload: dict) -> str:
    page_suffix = "" if page_num == 1 else f"/{page_num}"
    search_payload = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
    return (
        "https://message.alibaba.com/message/default.htm#feedback/all"
        f"{page_suffix}?search={quote(search_payload, safe='{}:,')}"
    )


def _build_time_range_url(
    page_num: int,
    start_time_ms: int,
    end_time_ms: int,
    owner_id: int | None = None,
    include_owner: bool = False,
) -> str:
    payload = {
        "startTime": str(int(start_time_ms)),
        "endTime": str(int(end_time_ms)),
    }
    if include_owner and owner_id is not None:
        payload["owner"] = int(owner_id)
    return _build_search_url(page_num, payload)


def _build_buyer_name_url(page_num: int, buyer_name: str) -> str:
    return _build_search_url(page_num, {"senderName": buyer_name})


def _build_default_list_url(page_num: int, owner_id: int | None = None) -> str:
    page_suffix = "" if page_num == 1 else f"/|{page_num}"
    url = f"{DEFAULT_LIST_URL}{page_suffix}"
    if owner_id is not None:
        url += f'?search={{"owner":{int(owner_id)}}}'
    return url


def build_url(
    page_num: int,
    owner_id: int | None = None,
    start_time_ms: int | None = None,
    end_time_ms: int | None = None,
    include_owner_with_time: bool = False,
    buyer_name: str = "",
) -> str:
    if buyer_name:
        return _build_buyer_name_url(page_num, buyer_name)

    if start_time_ms is not None and end_time_ms is not None:
        return _build_time_range_url(
            page_num,
            start_time_ms,
            end_time_ms,
            owner_id=owner_id,
            include_owner=include_owner_with_time,
        )

    return _build_default_list_url(page_num, owner_id=owner_id)


SEL = {
    "list_item": "[class*='inquiry-item']",
    "inquiry_id": "[class*='spec-inquiry-id']",
    "time_row": "[class*='m-header-padding']:not([class*='spec-inquiry'])",
    "buyer_name": ".aui2-grid-name",
    "product_name": ".buyer-product-name-content",
    "last_msg": ".buyer-chat-msg",
    "category": "[class*='aui-grid-category']",
    "assignee": "[class*='owner-name'], .aui2-grid-owner .aui-menu-trigger, [class*='owner'] [class*='name']",
    "country_flag": ".ui2-flag",
    "user_level_icon": ".spec-icon-wrap .aui-icon-buyer-level, .spec-icon-wrap .level-tag-icon",
    "no_data_notice": "text=暂无数据展示",
}


def get_list_item_selector() -> str:
    return SEL["list_item"]


def get_time_row_selector() -> str:
    return SEL["time_row"]


def get_inquiry_id_selector() -> str:
    return SEL["inquiry_id"]
