"""
rebuild_edges_existing_nodes.py
===============================
Rebuild edge SIMILAR_* untuk node existing memakai worker orchestration saat ini.
"""

import os
import threading
from dotenv import load_dotenv
from neo4j import GraphDatabase

from app.services.ingestion import create_gateway_llm_client, worker_edge_generator, task_queue


def main() -> int:
    load_dotenv()

    uri = os.getenv("NEO4J_URI", "")
    user = os.getenv("NEO4J_USERNAME", "neo4j")
    pwd = os.getenv("NEO4J_PASSWORD", "")

    if not all([uri, user, pwd]):
        print("❌ ERROR: Kredensial Neo4j belum lengkap di file .env")
        return 1

    driver = GraphDatabase.driver(uri, auth=(user, pwd))
    client = create_gateway_llm_client()

    with driver.session() as session:
        rows = list(session.run("MATCH (n:Literature) RETURN elementId(n) AS id ORDER BY n.title"))
    node_ids = [r["id"] for r in rows]

    print(f"Found nodes for edge rebuild: {len(node_ids)}")
    if not node_ids:
        driver.close()
        return 0

    worker = threading.Thread(target=worker_edge_generator, args=(driver, client), daemon=True)
    worker.start()

    for nid in node_ids:
        task_queue.put(nid)

    task_queue.put(None)
    task_queue.join()
    worker.join()
    driver.close()

    print("✅ Edge rebuild for existing nodes completed.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
