
import os
import sys
from datetime import datetime

# Add the backend directory to sys.path so we can import src modules
sys.path.append(os.path.join(os.path.dirname(__file__), '../../'))

from src.mongo.connection import get_mongo_client
from src.routes.incidents import save_to_chromadb

def sync_incidents():
    print("Starting sync of incidents from MongoDB to ChromaDB...")
    
    client = get_mongo_client()
    db = client["ethix"]
    collection = db["incidents"]
    
    # Find all confirmed greenwashing incidents
    cursor = collection.find({"is_greenwashing": True})
    
    count = 0
    synced = 0
    errors = 0
    
    for incident in cursor:
        count += 1
        incident_id = str(incident["_id"])
        product_name = incident.get("product_name", "Unknown")
        print(f"Processing Incident #{incident_id} ({product_name})...")
        
        try:
            # Convert ObjectId to string for the function if needed, 
            # but save_to_chromadb expects the dict and the id string.
            # Convert _id in dict to string just in case
            incident["_id"] = incident_id
            
            save_to_chromadb(incident, incident_id)
            synced += 1
            print(f" -> Successfully synced.")
        except Exception as e:
            errors += 1
            print(f" -> FAILED to sync: {e}")
            
    print(f"\nSync Complete.")
    print(f"Total processed: {count}")
    print(f"Successfully synced: {synced}")
    print(f"Errors: {errors}")

if __name__ == "__main__":
    sync_incidents()
