#!/usr/bin/env python3
"""Recreate a minimal Typesense test environment for a bug repro.

- Expects a Typesense server running at http://localhost:8108
- Expects TYPESENSE_API_KEY env var to be set
- Recreates the `public_places` collection and inserts a small fixture
"""

import json
import os
import sys
import urllib.error
import urllib.request

TYPESENSE_URL = "http://localhost:8108"
COLLECTION_NAME = "public_places"


def get_api_key():
    api_key = os.environ.get("TYPESENSE_API_KEY")
    if not api_key:
        sys.stderr.write("ERROR: TYPESENSE_API_KEY environment variable is not set.\n")
        sys.exit(1)
    return api_key


# ----- Captured schema from prod -----

SCHEMA = {
    "created_at": 1763114248,
    "default_sorting_field": "",
    "enable_nested_fields": True,
    "fields": [
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "",
            "name": "name.primary",
            "optional": False,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "en",
            "name": "name.en_us",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "fr",
            "name": "name.fr_fr",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "ru",
            "name": "name.ru_ru",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "id",
            "name": "name.id_id",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "it",
            "name": "name.it_it",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "ja",
            "name": "name.ja_jp",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "km",
            "name": "name.km_kh",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "ko",
            "name": "name.ko_kr",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "lt",
            "name": "name.lt_lt",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "ro",
            "name": "name.ro_ro",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "vi",
            "name": "name.vi_vn",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "zh",
            "name": "name.zh_cn",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "hr",
            "name": "name.hr_hr",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "cs",
            "name": "name.cs_cz",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "da",
            "name": "name.da_dk",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "nl",
            "name": "name.nl_nl",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "et",
            "name": "name.et_et",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "fi",
            "name": "name.fi_fi",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "el",
            "name": "name.el_gr",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "hu",
            "name": "name.hu_hu",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "lv",
            "name": "name.lv_lv",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "nb",
            "name": "name.nb",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "pl",
            "name": "name.pl_pl",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "pt",
            "name": "name.pt_pt",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "sr",
            "name": "name.sr_cyrl",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "sk",
            "name": "name.sk_sk",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "sl",
            "name": "name.sl_si",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "es",
            "name": "name.es_es",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "sv",
            "name": "name.sv_se",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "th",
            "name": "name.th_th",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "tr",
            "name": "name.tr_tr",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "uk",
            "name": "name.uk_ua",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "",
            "name": "address.country",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "",
            "name": "category",
            "optional": False,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "",
            "name": "center",
            "optional": False,
            "sort": True,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "geopoint",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "",
            "name": "address.sub_administrative_area",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
        {
            "facet": False,
            "index": True,
            "infix": False,
            "locale": "",
            "name": "address.administrative_area",
            "optional": True,
            "sort": False,
            "stem": False,
            "stem_dictionary": "",
            "store": True,
            "type": "string",
        },
    ],
    "name": "public_places",
    "num_documents": 76730019,
    "symbols_to_index": [],
    "token_separators": [],
}

# ----- Captured documents from prod -----

DOCUMENTS = [
    {
        "address": {
            "administrative_area": "Київ",
            "country": "Україна",
            "inland_water": None,
            "iso_country_code": "UA",
            "locality": "Київ",
            "ocean": None,
            "postal_code": "03150",
            "source": "Apple",
            "sub_administrative_area": None,
            "sub_locality": None,
            "sub_thoroughfare": None,
            "thoroughfare": "Ковпака вулиця",
        },
        "category": "Landmark",
        "center": [50.417667, 30.529097],
        "id": "56e4c80100000000",
        "name": {"primary": "Эйфелева башня Киев"},
    },
    {
        "address": {
            "administrative_area": "Санкт-Петербург",
            "country": "Россия",
            "inland_water": None,
            "iso_country_code": "RU",
            "locality": "Санкт-Петербург",
            "ocean": None,
            "postal_code": "197350",
            "source": "Apple",
            "sub_administrative_area": None,
            "sub_locality": "Жк Юбилейный Квартал",
            "sub_thoroughfare": "50 с1",
            "thoroughfare": "Парашютная улица",
        },
        "category": "Bakery",
        "center": [60.0342153, 30.2462626],
        "id": "b80bdc0000000000",
        "name": {"primary": "Эйфелева башня, булочная-кондитерская"},
    },
    {
        "address": {
            "administrative_area": "Курская область",
            "country": "Россия",
            "inland_water": None,
            "iso_country_code": "RU",
            "locality": "Железногорск",
            "ocean": None,
            "postal_code": "302520",
            "source": "Apple",
            "sub_administrative_area": "Городской Округ Железногорск",
            "sub_locality": "5-й Мкр",
            "sub_thoroughfare": "37",
            "thoroughfare": "улица Ленина",
        },
        "category": "Landmark",
        "center": [52.336971, 35.351725],
        "id": "7ea96b0100000000",
        "name": {"primary": "Железногорская Эйфелева башня"},
    },
    {
        "address": {
            "administrative_area": "Москва",
            "country": "Россия",
            "inland_water": None,
            "iso_country_code": "RU",
            "locality": "Москва",
            "ocean": None,
            "postal_code": "125239",
            "source": "Apple",
            "sub_administrative_area": None,
            "sub_locality": "Район Коптево",
            "sub_thoroughfare": "69А с5",
            "thoroughfare": "Коптевская улица",
        },
        "category": "Landmark",
        "center": [55.831439, 37.516217],
        "id": "6c108d0300000000",
        "name": {"primary": "Эйфелева Башня"},
    },
    {
        "address": {
            "administrative_area": "Свердловская область",
            "country": "Россия",
            "inland_water": None,
            "iso_country_code": "ru",
            "locality": None,
            "ocean": None,
            "postal_code": "624053",
            "source": "OpenCage",
            "sub_administrative_area": "городской округ Верхнее Дуброво",
            "sub_locality": None,
            "sub_thoroughfare": None,
            "thoroughfare": "unnamed road",
        },
        "category": "Landmark",
        "center": [56.764625549316406, 61.06346893310547],
        "id": "ab22980000000000",
        "name": {"primary": "Эйфелева башня"},
    },
    {
        "address": {
            "administrative_area": "Almaty",
            "country": "Kazakhstan",
            "inland_water": None,
            "iso_country_code": "KZ",
            "locality": "Almaty",
            "ocean": None,
            "postal_code": None,
            "source": "Apple",
            "sub_administrative_area": None,
            "sub_locality": None,
            "sub_thoroughfare": None,
            "thoroughfare": "Nazarbayev Avenue",
        },
        "category": "Landmark",
        "center": [43.2444205, 76.9480601],
        "id": "f41b350300000000",
        "name": {"primary": "Эйфелева башня"},
    },
    {
        "address": {
            "administrative_area": "Иркутская область",
            "country": "Россия",
            "inland_water": None,
            "iso_country_code": "RU",
            "locality": "Иркутск",
            "ocean": None,
            "postal_code": "664003",
            "source": "Apple",
            "sub_administrative_area": "Городской Округ Иркутск",
            "sub_locality": "Правобережный",
            "sub_thoroughfare": "9",
            "thoroughfare": "улица Урицкого",
        },
        "category": "Landmark",
        "center": [52.28395, 104.29123],
        "id": "53578d0100000000",
        "name": {"primary": "Эйфелева башня"},
    },
    {
        "address": {
            "administrative_area": None,
            "country": None,
            "inland_water": None,
            "iso_country_code": None,
            "locality": None,
            "ocean": None,
            "postal_code": "75007",
            "source": "TrustedUnknown",
            "sub_administrative_area": "Paris",
            "sub_locality": None,
            "sub_thoroughfare": "5",
            "thoroughfare": "Avenue Anatole France",
        },
        "category": "Landmark",
        "center": [48.85826110839844, 2.29450061917305],
        "id": "83300a0000000000",
        "name": {
            "cs_cz": "Eiffelova věž",
            "da_dk": "Eiffeltårnet",
            "el_gr": "Πύργος του Άιφελ",
            "en_us": "Eiffel Tower",
            "es_es": "Torre Eiffel",
            "et_et": "Eiffeli torn",
            "fi_fi": "Eiffel-torni",
            "fr_fr": "Tour Eiffel",
            "hr_hr": "Eiffelov toranj",
            "hu_hu": "Eiffel-torony",
            "id_id": "Menara Eiffel",
            "it_it": "Torre Eiffel",
            "ja_jp": "エッフェル塔",
            "ko_kr": "에펠탑",
            "nl_nl": "Eiffeltoren",
            "pl_pl": "Wieża Eiffla",
            "primary": "Tour Eiffel",
            "pt_pt": "Torre Eiffel",
            "ro_ro": "Turnul Eiffel",
            "ru_ru": "Эйфелева башня",
            "sk_sk": "Eiffelova veža",
            "sl_si": "Eifflov stolp",
            "sr_cyrl": "Ајфелова кула",
            "sv_se": "Eiffeltornet",
            "tr_tr": "Eyfel Kulesi",
            "uk_ua": "Ейфелева вежа",
            "vi_vn": "Tháp Eiffel",
            "zh_cn": "埃菲尔铁塔",
        },
    },
    {
        "address": {
            "administrative_area": "Стара Загора",
            "country": "България",
            "inland_water": None,
            "iso_country_code": "BG",
            "locality": "Павел баня",
            "ocean": None,
            "postal_code": "6155",
            "source": "Apple",
            "sub_administrative_area": None,
            "sub_locality": "Павел баня",
            "sub_thoroughfare": "4",
            "thoroughfare": "Ген. Столетов",
        },
        "category": "School",
        "center": [42.6006828, 25.2051868],
        "id": "980f170300000000",
        "name": {"primary": "АПИ База за квалификация и преквалификация на кадри"},
    },
    {
        "address": {
            "administrative_area": "Кюстендил",
            "country": "България",
            "inland_water": None,
            "iso_country_code": "BG",
            "locality": "Паничище",
            "ocean": None,
            "postal_code": "2650",
            "source": "Apple",
            "sub_administrative_area": None,
            "sub_locality": "Сапарева баня",
            "sub_thoroughfare": "3",
            "thoroughfare": "Здравец",
        },
        "category": "School",
        "center": [42.2867756, 23.2582071],
        "id": "ac16a00200000000",
        "name": {"primary": "Училище Христо Ботев"},
    },
    {
        "address": {
            "administrative_area": "Кюстендил",
            "country": "България",
            "inland_water": None,
            "iso_country_code": "BG",
            "locality": "Паничище",
            "ocean": None,
            "postal_code": "2650",
            "source": "Apple",
            "sub_administrative_area": None,
            "sub_locality": "Сапарева баня",
            "sub_thoroughfare": "5",
            "thoroughfare": "Димитър Чучуганов",
        },
        "category": "School",
        "center": [42.2888983, 23.2663944],
        "id": "36ba080400000000",
        "name": {"primary": "СПТУ Христо Ботев"},
    },
    {
        "address": {
            "administrative_area": "Кюстендил",
            "country": "България",
            "inland_water": None,
            "iso_country_code": "BG",
            "locality": "Паничище",
            "ocean": None,
            "postal_code": "2650",
            "source": "Apple",
            "sub_administrative_area": None,
            "sub_locality": "Сапарева баня",
            "sub_thoroughfare": "10",
            "thoroughfare": "Отец Паисий",
        },
        "category": "School",
        "center": [42.2912256, 23.2673378],
        "id": "334f740400000000",
        "name": {"primary": "Childrens Day Care"},
    },
    {
        "address": {
            "administrative_area": "Санкт-Петербург",
            "country": "Россия",
            "inland_water": None,
            "iso_country_code": "RU",
            "locality": "Санкт-Петербург",
            "ocean": None,
            "postal_code": "191186",
            "source": "Apple",
            "sub_administrative_area": None,
            "sub_locality": "Муниципальный Округ Дворцовый Округ",
            "sub_thoroughfare": "6",
            "thoroughfare": "Дворцовая набережная",
        },
        "category": "Restaurant",
        "center": [59.945133, 30.326692],
        "id": "7116dc0000000000",
        "name": {"primary": "Эйфелев мост", "ru_ru": "Эйфелев мост"},
    },
]


def api_call(method: str, path: str, body=None):
    if not path.startswith("/"):
        path = "/" + path

    url = TYPESENSE_URL + path
    api_key = get_api_key()

    headers = {"X-TYPESENSE-API-KEY": api_key}
    data = None
    if body is not None:
        headers["Content-Type"] = "application/json"
        data = json.dumps(body).encode("utf-8")

    req = urllib.request.Request(url, data=data, headers=headers, method=method)

    try:
        with urllib.request.urlopen(req) as resp:
            raw = resp.read().decode("utf-8")
            if not raw:
                return None
            try:
                return json.loads(raw)
            except json.JSONDecodeError:
                return raw
    except urllib.error.HTTPError as e:
        body = e.read().decode("utf-8", errors="replace")
        sys.stderr.write(f"HTTP {e.code} for {method} {path}\n{body}\n")
        raise
    except urllib.error.URLError as e:
        sys.stderr.write(f"Network error calling {method} {path}: {e}\n")
        raise


def delete_collection_if_exists():
    try:
        api_call("DELETE", f"/collections/{COLLECTION_NAME}")
        print(f"Deleted existing collection {COLLECTION_NAME!r}")
    except urllib.error.HTTPError as e:
        # 404 means collection doesn't exist yet: that's fine.
        if e.code == 404:
            print(f"Collection {COLLECTION_NAME!r} did not exist before setup.")
            return
        raise


def create_collection():
    # Some Typesense versions might not like extra metadata fields in the schema;
    # if needed, here's where you'd strip them. For now, we send SCHEMA as-is.
    print(f"Creating collection {COLLECTION_NAME!r}...")
    resp = api_call("POST", "/collections", SCHEMA)
    print("Create collection response:", resp)


def import_documents():
    print(f"Importing {len(DOCUMENTS)} document(s)...")
    for i, doc in enumerate(DOCUMENTS, 1):
        print(f"  [{i}/{len(DOCUMENTS)}] id={doc.get('id')!r}")
        api_call("POST", f"/collections/{COLLECTION_NAME}/documents", doc)
    print("Done importing documents.")


def main():
    delete_collection_if_exists()
    create_collection()
    import_documents()
    print("Setup complete. You can now run your reproduction steps.")


if __name__ == "__main__":
    main()
