#!/usr/bin/env python3
"""连接 ES，选一个索引并搜索前 50 条。用法: ES_HOSTS=... ES_SKIP_PRODUCT_CHECK=1 uv run python scripts/search_first_50.py [索引名]"""
from __future__ import annotations

import base64
import json
import os
import sys
import urllib.request

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))

from elasticsearch_client_mcp.config import load_connection_map, load_safety_config
from elasticsearch_client_mcp.client import connect, list_indices


def _search_http(base_url: str, index: str, body: dict, auth: tuple[str, str] | None) -> dict:
    """用 application/json 发搜索，兼容 ES 7.x"""
    url = f"{base_url.rstrip('/')}/{index}/_search"
    data = json.dumps(body).encode("utf-8")
    req = urllib.request.Request(
        url, data=data, method="POST",
        headers={"Content-Type": "application/json", "Accept": "application/json"},
    )
    if auth:
        b64 = base64.b64encode(f"{auth[0]}:{auth[1]}".encode()).decode()
        req.add_header("Authorization", f"Basic {b64}")
    with urllib.request.urlopen(req, timeout=30) as resp:
        return json.load(resp)


def main() -> None:
    index = (sys.argv[1:] or [None])[0]
    default, _, _ = load_connection_map()
    safety = load_safety_config()
    scheme = "https" if default.use_ssl else "http"
    base_url = f"{scheme}://{default.host}:{default.port}"
    auth = (default.user, default.password) if default.user else None

    with connect(default, safety) as client:
        if not index:
            indices = list_indices(client, "*")
            candidates = [x["name"] for x in indices if not x["name"].startswith(".")]
            if not candidates:
                print("没有找到非系统索引")
                return
            index = candidates[0]
            print(f"使用索引: {index}\n")

    size = int(os.environ.get("ES_SEARCH_SIZE", "50"))
    body = {"size": size, "query": {"match_all": {}}}
    out = _search_http(base_url, index, body, auth)
    total = out.get("hits", {}).get("total")
    if isinstance(total, dict):
        total = total.get("value", 0)
    else:
        total = total or 0
    hits = out.get("hits", {}).get("hits", [])
    print(f"共 {total} 条，返回前 {len(hits)} 条:\n")
    for i, h in enumerate(hits, 1):
        src = h.get("_source") or {}
        print(f"--- [{i}] _id={h.get('_id')} ---")
        print(json.dumps(src, ensure_ascii=False, indent=2, default=str))
        print()
    print("ok")


if __name__ == "__main__":
    main()
