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 Harken.API.dlete_product import delete_shopify_product
from Harken.API.tokens import access_tokens
from Harken.API.get_all_products import get_all_products

SHOP_NAME = 'https://harkenb2b.myshopify.com/'
API_VERSION = '2024-10'

def collect_duplicates(data):
    sku_details = {}

    for product in data.get("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] = {}
                sku_details[sku][product_id] = updated_at

    duplicates_to_delete = []

    for sku, products in sku_details.items():
        if len(products) > 1:
            latest_id = None
            latest_date = None
            for pid, date_str in products.items():
                try:
                    dt = datetime.fromisoformat(date_str)
                except Exception:
                    continue
                if not latest_date or dt > latest_date:
                    latest_date = dt
                    latest_id = pid
            for pid in products:
                if pid != latest_id:
                    duplicates_to_delete.append((sku, pid, products[pid]))

    return duplicates_to_delete

async def delete_product_limited(session, product_id, sku, date, token, semaphore):
    async with semaphore:
        print(f"🗑 Suppression du produit {product_id} (SKU {sku}, mis à jour {date})")
        result = await delete_shopify_product(session, product_id, token)
        print(f"✅ Résultat suppression {product_id} : {result}")
        await asyncio.sleep(0.5)  # Shopify = max 2 req/sec/token

async def delete_duplicates(session, token, semaphore):
    with open('products.json', 'r', encoding='ISO-8859-1') as file:
        data = json.load(file)

    print(f"📦 Total produits chargés : {len(data.get('products', []))}")
    duplicates = collect_duplicates(data)
    print(f"🔍 Produits à supprimer : {len(duplicates)}")

    tasks = []
    for sku, pid, date in duplicates:
        tasks.append(delete_product_limited(session, pid, sku, date, token, semaphore))

    # Exécuter par batchs de 10 pour limiter la charge mémoire
    for i in range(0, len(tasks), 10):
        batch = tasks[i:i+10]
        await asyncio.gather(*batch)

async def main():
    await get_all_products(access_tokens, SHOP_NAME, API_VERSION)
    token = access_tokens[0]
    semaphore = asyncio.Semaphore(2)  # Limite à 2 appels/sec

    async with aiohttp.ClientSession() as session:
        await delete_duplicates(session, token, semaphore)

if __name__ == '__main__':
    asyncio.run(main())
