"""
Ricostruisce l'indice FAISS prodotti dai metadati puliti.

Input:  artifacts/metadata_cleaned.json
Output: artifacts/faiss_products/

Tempo stimato: 3-5 minuti (100k embeddings).
"""
import json
import os
import sys
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_core.documents import Document

PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INPUT_FILE = os.path.join(PROJECT_ROOT, "artifacts", "metadata_cleaned.json")
INDEX_NAME = os.path.join(PROJECT_ROOT, "artifacts", "faiss_products")


def build_index():
    print("--- CREAZIONE INDICE DI RICERCA (FAISS) ---")

    if not os.path.exists(INPUT_FILE):
        print(f"Errore: {INPUT_FILE} non trovato!")
        sys.exit(1)

    print("-> Caricamento prodotti puliti...")
    with open(INPUT_FILE, "r", encoding="utf-8") as f:
        products = json.load(f)

    print(f"-> Preparazione documenti ({len(products)} items)...")
    docs = []
    for p in products:
        page_content = f"{p['title']} {p['brand']} {' '.join(str(c) for c in p['categories'])}"
        meta = {
            "asin": p["asin"],
            "title": p["title"],
            "price": str(p["price"]),
            "brand": p["brand"],
            "image_url": p["image_url"],
        }
        docs.append(Document(page_content=page_content, metadata=meta))

    print("-> Calcolo Embeddings e Indicizzazione (puo' richiedere qualche minuto)...")
    embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
    vectorstore = FAISS.from_documents(docs, embeddings)

    vectorstore.save_local(INDEX_NAME)
    print(f"Indice salvato in: {INDEX_NAME}")


if __name__ == "__main__":
    build_index()
