import json
import os
import sys
import asyncio
from datetime import datetime
import aiohttp


sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from api.products import delete_shopify_product
from api.products import  get_all_products
shop_name = 'https://harkenb2b.myshopify.com/'
async def delete_duplicates():
    await get_all_products()
    with open('products.json', 'r', encoding='utf-8') as f:
        products = json.load(f)

    # Structure pour stocker pour chaque SKU un dictionnaire de produits uniques
    sku_details = {}

    # Parcourir les produits et leurs variantes
    for product in products:
        product_id = product.get("id")
        updated_at = product.get("updated_at")
        for variant in product.get("variants", []):
            sku = variant.get("sku")
            if sku:
                if sku not in sku_details:
                    sku_details[sku] = {'products': {}}
                # Ajouter le produit une seule fois par SKU
                if product_id not in sku_details[sku]['products']:
                    sku_details[sku]['products'][product_id] = updated_at

    print("Doublons de SKU (tous sauf le produit le plus récent) :")
    print(f"Nombre total de produits chargés : {len(products)}")

    # Créer une session aiohttp pour les appels API
    async with aiohttp.ClientSession() as session:
        for sku, details in sku_details.items():
            if len(details['products']) > 1:
                # Identifier le produit le plus récent
                latest_product = None
                latest_date = None
                for pid, update_str in details['products'].items():
                    try:
                        dt = datetime.fromisoformat(update_str)
                    except Exception:
                        continue
                    if latest_date is None or dt > latest_date:
                        latest_date = dt
                        latest_product = pid
                # Parcourir tous les produits sauf le produit le plus récent
                for pid, update_str in details['products'].items():
                    if pid != latest_product:
                        try:
                            dt = datetime.fromisoformat(update_str)
                        except Exception:
                            continue
                        print(f"SKU '{sku}' - Produit ID: {pid}, Date de mise à jour: {dt}")
                        # Suppression du produit (limite de 2 appels par seconde)
                        result = await delete_shopify_product(session, pid, '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')
                        print(f"Suppression du produit {pid} :", result)
                        await asyncio.sleep(0.5)


if __name__ == '__main__':
    asyncio.run(delete_duplicates())
    sys.exit(0)
