from __future__ import annotations

from dataclasses import dataclass

FILTER_FIELD_ORDER = ("sort_by", "note_type", "publish_time", "search_scope", "location")

_FILTER_CONFIG = {
    "sort_by": {
        "aliases": {
            "comprehensive": "comprehensive",
            "综合": "comprehensive",
            "latest": "latest",
            "最新": "latest",
            "most_liked": "most_liked",
            "最多点赞": "most_liked",
            "most_commented": "most_commented",
            "最多评论": "most_commented",
            "most_favorited": "most_favorited",
            "最多收藏": "most_favorited",
        },
        "selectors": {
            "comprehensive": (1, 1, "综合"),
            "latest": (1, 2, "最新"),
            "most_liked": (1, 3, "最多点赞"),
            "most_commented": (1, 4, "最多评论"),
            "most_favorited": (1, 5, "最多收藏"),
        },
    },
    "note_type": {
        "aliases": {
            "all": "all",
            "不限": "all",
            "video": "video",
            "视频": "video",
            "image_text": "image_text",
            "图文": "image_text",
        },
        "selectors": {
            "all": (2, 1, "不限"),
            "video": (2, 2, "视频"),
            "image_text": (2, 3, "图文"),
        },
    },
    "publish_time": {
        "aliases": {
            "all": "all",
            "不限": "all",
            "day": "day",
            "一天内": "day",
            "week": "week",
            "一周内": "week",
            "half_year": "half_year",
            "半年内": "half_year",
        },
        "selectors": {
            "all": (3, 1, "不限"),
            "day": (3, 2, "一天内"),
            "week": (3, 3, "一周内"),
            "half_year": (3, 4, "半年内"),
        },
    },
    "search_scope": {
        "aliases": {
            "all": "all",
            "不限": "all",
            "viewed": "viewed",
            "已看过": "viewed",
            "unviewed": "unviewed",
            "未看过": "unviewed",
            "following": "following",
            "已关注": "following",
        },
        "selectors": {
            "all": (4, 1, "不限"),
            "viewed": (4, 2, "已看过"),
            "unviewed": (4, 3, "未看过"),
            "following": (4, 4, "已关注"),
        },
    },
    "location": {
        "aliases": {
            "all": "all",
            "不限": "all",
            "local": "local",
            "同城": "local",
            "nearby": "nearby",
            "附近": "nearby",
        },
        "selectors": {
            "all": (5, 1, "不限"),
            "local": (5, 2, "同城"),
            "nearby": (5, 3, "附近"),
        },
    },
}


@dataclass(frozen=True)
class SearchFilterSelection:
    field: str
    value: str
    filters_index: int
    tags_index: int
    label: str


def normalize_filter_value(field: str, value: str | None) -> str | None:
    if value is None:
        return None
    text = str(value).strip()
    if not text:
        return None
    config = _FILTER_CONFIG.get(field)
    if config is None:
        raise ValueError(f"未知筛选字段: {field}")
    aliases = config["aliases"]
    normalized = aliases.get(text) or aliases.get(text.lower())
    if normalized:
        return normalized
    canonical = sorted(config["selectors"].keys())
    raise ValueError(f"{field} 不支持 '{text}'，可选值: {', '.join(canonical)}")


def build_search_filter_selections(
    *,
    sort_by: str | None = None,
    note_type: str | None = None,
    publish_time: str | None = None,
    search_scope: str | None = None,
    location: str | None = None,
) -> list[SearchFilterSelection]:
    values = {
        "sort_by": sort_by,
        "note_type": note_type,
        "publish_time": publish_time,
        "search_scope": search_scope,
        "location": location,
    }
    selections: list[SearchFilterSelection] = []
    for field in FILTER_FIELD_ORDER:
        value = values[field]
        if not value:
            continue
        selectors = _FILTER_CONFIG[field]["selectors"]
        filters_index, tags_index, label = selectors[value]
        selections.append(
            SearchFilterSelection(
                field=field,
                value=value,
                filters_index=filters_index,
                tags_index=tags_index,
                label=label,
            )
        )
    return selections
