import asyncio
from dot_search import SearchEngine, TableConfig, EmbeddingConfig, BM25Config, ExactConfig


async def main():
    engine = SearchEngine(db_url="postgresql+asyncpg://user:pass@localhost/mydb")

    # --- Index: multiple embeddings + BM25 + exact ---
    await engine.index(config=TableConfig(
        table="articles",
        pk_column="id",                 # defaults to "id" if omitted
        batch_size=100,                 # defaults to 500 if omitted
        embeddings=[
            EmbeddingConfig(
                source_column="body",
                target_column="ds_body",
            ),
            EmbeddingConfig(
                source_column="title",
                target_column="ds_title",
            ),
        ],
        bm25=[
            BM25Config(source_column="title"),
            BM25Config(source_column="body"),
        ],
        exact=[ExactConfig(source_column="name")],
    ))

    # --- Index 2: title-only, separate index_id on the same table ---
    await engine.index(config=TableConfig(
        table="articles",
        index_id="article_titles",
        embeddings=[
            EmbeddingConfig(
                source_column="title",
                target_column="ds_article_titles_title",
            ),
        ],
    ))

    # --- Re-index when new rows arrive ---
    await engine.index(index_id="articles")        # reloads saved config, re-embeds all rows
    await engine.index(index_id="article_titles")

    # --- Search: hybrid (vector + BM25 + exact), SQL filter, per-query weight overrides ---
    print("=== Hybrid search ===")
    results = await engine.search(
        "fermentation and gut health",
        "articles",
        limit=10,
        where="published_year >= 2022 AND topic = 'health'",
        embedding_weights={
            "ds_body": 1.0,
            "ds_title": 0.3,
        },
        bm25_weights={"title": 0.5, "body": 2.0},
    )
    for r in results:
        print(r)

    # --- Search: BM25-only ---
    print("=== BM25-only search ===")
    results = await engine.search("fermentation", "articles", strategy="bm25", limit=5)
    for r in results:
        print(r)

    # --- Search: exact-only ---
    print("=== Exact search ===")
    results = await engine.search("Dupont", "articles", strategy="exact", limit=5)
    for r in results:
        print(r)

    # --- Search: title-only index ---
    print("=== Title-only index search ===")
    results = await engine.search("gut health", "article_titles", limit=5)
    for r in results:
        print(r)


asyncio.run(main())
