import time
import os
import sys
from app.core.index import faiss_index

def watch_and_reload(user_id: str, interval=600):
    index_file = os.path.join("index_data", f"{user_id}.index")
    print(f"[HOT-RELOAD] Watching {index_file} for updates...")
    last_mtime = None

    while True:
        try:
            mtime = os.path.getmtime(index_file)
            if last_mtime is None:
                last_mtime = mtime
            elif mtime != last_mtime:
                print("[HOT-RELOAD] Detected new index file. Reloading...")
                faiss_index.update_index(index_file)
                last_mtime = mtime
        except Exception as e:
            print(f"[HOT-RELOAD] Error: {e}")
        time.sleep(interval)

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python -m scripts.update_index <user_id>")
        sys.exit(1)

    user_id = sys.argv[1]
    watch_and_reload(user_id)
