"""Bounded batch search with pagination and retries. pip install requests

Keep raw.py in the same directory. Use your token's actual rpm, not a plan name.
"""
import json
import os

from raw import MCP


def pages(client, query, court, max_pages=2):
    cursor = 0
    session = ""
    for _ in range(max_pages):
        result = client.call("kas_search", {
            "phrase": query, "court": court, "kind": "civil", "detail": "brief",
            "limit": 2, "cursor": cursor, "session": session,
        })
        session = result.get("session", session)  # Tool workflow ID, distinct from MCP header.
        yield result
        if result.get("частично"):
            raise RuntimeError("Partial search: narrow the query before treating this as complete")
        following = result.get("page", {}).get("next_cursor")
        if following is None:
            return
        if following <= cursor:
            raise RuntimeError("Cursor did not advance")
        cursor = following
    # An explicit application bound: max_pages is not corpus exhaustion.


def main():
    client = MCP(os.environ["AMAZINGCAT_TOKEN"], rpm=int(os.getenv("AMAZINGCAT_RPM", "200")))
    try:
        client.initialize()
        for query in ("возврат товара", "расторжение договора"):
            for page in pages(client, query, court=1):
                print(json.dumps({"query": query, "found": page.get("найдено"),
                                  "shown": page.get("показано"), "page": page.get("page")},
                                 ensure_ascii=False))
    finally:
        client.close()


if __name__ == "__main__":
    main()
