"""Test: Kiểm tra embedding search có match được sai chính tả không"""
import asyncio
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common.embedding_service import create_embedding_async
from common.starrocks_connection import get_db_connection

output_lines = []

async def search_products(query_text, sr):
    v = await create_embedding_async(query_text)
    if not v:
        output_lines.append("  ERROR: embedding failed")
        return
    v_str = "[" + ",".join(str(x) for x in v) + "]"
    sql = f"""
    SELECT magento_ref_code, product_name, master_color, gender_by_product, age_by_product,
        approx_cosine_similarity(vector, {v_str}) as score
    FROM shared_source.magento_product_dimension_with_text_embedding
    ORDER BY score DESC LIMIT 5
    """
    rows = await sr.execute_query_async(sql)
    for i, r in enumerate(rows):
        line = f"  #{i+1} [score={r.get('score','?'):.4f}] {r['magento_ref_code']} | {r['product_name']} | {r.get('master_color','')} | {r.get('gender_by_product','')}/{r.get('age_by_product','')}"
        output_lines.append(line)

async def main():
    sr = get_db_connection()
    tests = [
        "Ao khoac tran bong cho tre em",
        "Ao khoac chan bong cho tre em",
        "Ao khoac chan bong",
    ]
    for query in tests:
        output_lines.append("=" * 80)
        output_lines.append(f"QUERY: '{query}'")
        output_lines.append("-" * 80)
        await search_products(query, sr)
        output_lines.append("")

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
    loop.run_until_complete(main())
finally:
    loop.close()

# Write output with UTF-8
out_path = os.path.join(os.path.dirname(__file__), "test_output.txt")
with open(out_path, "w", encoding="utf-8") as f:
    f.write("\n".join(output_lines))
print(f"Output written to {out_path}")
