#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
================================================================================
 Nazev:   create_email_indexes_v1.0.py
 Verze:   1.0
 Datum:   2026-06-08
 Autor:   Vladimir Buzalka (asistovano Claude)
 Popis:   Vytvori slozene indexy na kolekci emailu vbuzalka@its.jnj.com
          v databazi `emaily` pro rychle vyhledavani:
            - { recipients.email: 1, received_at: -1 }  -> prijemce + datum
            - { sender.email:      1, received_at: -1 }  -> odesilatel + datum
          Indexy jsou v pozadi (background) a idempotentni (create_index
          nic neudela, kdyz uz existuji se stejnym klicem/nazvem).
 Pozn.:   Pred spustenim ukazat nahled; vytvoreni indexu je nedestruktivni.
================================================================================
"""

import sys
from datetime import datetime

from pymongo import MongoClient, ASCENDING, DESCENDING

MONGO_HOST = "192.168.1.76"
DB_NAME = "emaily"
COLLECTION = "vbuzalka@its.jnj.com"

INDEXES = [
    {
        "name": "recipients.email_1_received_at_-1",
        "keys": [("recipients.email", ASCENDING), ("received_at", DESCENDING)],
    },
    {
        "name": "sender.email_1_received_at_-1",
        "keys": [("sender.email", ASCENDING), ("received_at", DESCENDING)],
    },
]


def log(msg: str) -> None:
    print(f"[{datetime.now():%Y-%m-%d %H:%M:%S}] {msg}", flush=True)


def main() -> int:
    log(f"Pripojuji se k MongoDB ({MONGO_HOST}) ...")
    client = MongoClient(MONGO_HOST, serverSelectionTimeoutMS=5000)
    client.admin.command("ping")
    coll = client[DB_NAME][COLLECTION]
    log(f"OK. Kolekce {DB_NAME}.{COLLECTION} ma {coll.estimated_document_count():,} dokumentu.")

    log("Stavajici indexy:")
    for name, spec in coll.index_information().items():
        log(f"   - {name}: {spec.get('key')}")

    for idx in INDEXES:
        log(f"Vytvarim index '{idx['name']}' ...")
        created = coll.create_index(idx["keys"], name=idx["name"], background=True)
        log(f"   -> hotovo: {created}")

    log("Indexy po vytvoreni:")
    for name, spec in coll.index_information().items():
        log(f"   - {name}: {spec.get('key')}")

    client.close()
    log("Hotovo.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
