"""Server list search history — normalize and merge rules (DB payload shape)."""

from __future__ import annotations

MAX_SERVER_SEARCH_HISTORY = 12
MAX_PUSH_SEARCH_HISTORY = 5
MAX_TERMINAL_SEARCH_HISTORY = 10
MAX_SERVER_SEARCH_QUERY_LEN = 200
SERVERS_SEARCH_CONTEXT = "servers_search"
PUSH_SEARCH_CONTEXT = "push_search"
TERMINAL_SEARCH_CONTEXT = "terminal_search"


def normalize_search_query(query: str | None) -> str:
    return (query or "").strip()[:MAX_SERVER_SEARCH_QUERY_LEN]


def empty_search_state() -> dict:
    return {"history": [], "last": None}


def parse_search_state(raw: dict | None, *, max_history: int = MAX_SERVER_SEARCH_HISTORY) -> dict:
    if not raw:
        return empty_search_state()
    history_raw = raw.get("history")
    history: list[str] = []
    if isinstance(history_raw, list):
        for item in history_raw:
            if not isinstance(item, str):
                continue
            q = normalize_search_query(item)
            if q and q not in history:
                history.append(q)
            if len(history) >= max_history:
                break
    last_raw = raw.get("last")
    last = normalize_search_query(last_raw) if isinstance(last_raw, str) else ""
    last = last or None
    return {"history": history, "last": last}


def apply_search_record(state: dict, query: str, *, max_history: int = MAX_SERVER_SEARCH_HISTORY) -> dict:
    q = normalize_search_query(query)
    history = list(state.get("history") or [])
    if not q:
        return {"history": history, "last": None}
    history = [q] + [x for x in history if x != q][: max_history - 1]
    return {"history": history, "last": q}


def apply_search_replace(
    *,
    history: list[str],
    last: str | None = None,
    max_history: int = MAX_SERVER_SEARCH_HISTORY,
) -> dict:
    cleaned: list[str] = []
    for item in history:
        q = normalize_search_query(item)
        if q and q not in cleaned:
            cleaned.append(q)
        if len(cleaned) >= max_history:
            break
    last_norm = normalize_search_query(last) if last else ""
    last_val = last_norm or (cleaned[0] if cleaned else None)
    return {"history": cleaned, "last": last_val}
