import sys
import os
import csv
import json
import asyncio
import aiofiles

# Ajout du chemin pour importer les modules personnalisés
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
from Harken.API.BSS.api import get_all_rules, create_or_update_rule, upload_custom_pricing
from Harken.Tarifs.utils import find_existing_customer, find_rule_by_name

PRODUCTS_FILE_PATH_JSON = '../Products/products.json'
CUSTOMERS_FILE_PATH_JSON = '../Customers/Customers.json'
FILE_PATH_CSV = '../files/Tarifs/Tarifs-Branche-ES.csv'
BSS_API_KEY = 'qIm2Pdkz3Q8XmjA0THoXIhvxAhHTxhJxypclPP4Fjmo='
SHOP_NAME = 'https://harkenb2b.myshopify.com/'

# Chargement des fichiers JSON (synchrones)
with open(CUSTOMERS_FILE_PATH_JSON, 'r', encoding='ISO-8859-1') as f:
    customers = json.load(f)

async def main():
    count = 0
    # Récupération asynchrone des règles existantes
    try:
        rules_data = await asyncio.to_thread(get_all_rules, 'harkenb2b.myshopify.com', BSS_API_KEY)
        # rule_ids = [rule["id"] for rule in rules_data.get("rules", [])]
        # print(rule_ids)
        # exit()
        all_cp_rules = rules_data["rules"]
    except Exception as e:
        print("Error:", str(e))
        return

    tasks = []

    # Lecture asynchrone du fichier CSV via aiofiles
    async with aiofiles.open(FILE_PATH_CSV, mode='r', encoding='UTF-8') as afile:
        content = await afile.read()
    # Utilisation de StringIO pour parser le contenu CSV avec le module csv
    import io
    csvfile = io.StringIO(content)
    csv_reader = csv.reader(csvfile, delimiter=';')
    header = next(csv_reader)
    client_tags = header[1:]  # Les tags clients se trouvent à partir de la 4ème colonne

    async def process_discount(product_tag, client_tag, discount, count):
        print("Processing discount", product_tag, client_tag, discount, count)
        # Détermination de la priorité et du type de condition produit
        if product_tag == 'Base':
            priority = 30
            product_condition_type = 0
        elif product_tag.startswith('Classe:'):
            priority = 25
            product_condition_type = 3
        elif product_tag.startswith('Code Famille:'):
            priority = 20
            product_condition_type = 3
        elif product_tag.startswith('Marque:'):
            priority = 15
            product_condition_type = 3
        elif product_tag.startswith('Sous-Famille:'):
            priority = 10
            product_condition_type = 3

        if client_tag.startswith('Branche:'):
            priority -= 1
        elif client_tag.isdigit():
            priority -= 2
        print(f"{client_tag}: {priority}" )



        # Si le client_tag est numérique, on récupère l'id client via les clients existants
        if client_tag.isdigit():
            customer = find_existing_customer(customers, client_tag)
            client_tag = "Code Client : " +client_tag
            customer_id = customer['id'] if customer is not None else None
            rule_name = f" Client(s): {client_tag} --- Produit(s): {product_tag} --- Remise: {discount}"
            apply_to_customer_or_tag = 4
        else:
            customer_id = None  # Défini customer_id dans le cas où le client_tag n'est pas numérique
            rule_name = f"Client(s): {client_tag} --- Produit(s): {product_tag} --- Remise: {discount}"
            apply_to_customer_or_tag = 4

        # Conversion de la remise en float (en gérant la virgule comme séparateur décimal)
        discount_float = float(discount.replace('%', '').replace('\xa0', '').replace(',', '.').replace('ï¿½', '').strip())
        # Recherche d'une règle existante
        founded_rule = find_rule_by_name(rule_name, all_cp_rules)
        print(founded_rule)

        rule_id = founded_rule['id'] if founded_rule else None

        await asyncio.to_thread(
            create_or_update_rule,
            priority,
            product_condition_type,
            apply_to_customer_or_tag,
            rule_name,
            client_tag,
            product_tag,
            customer_id,
            discount_float,
            rule_id,
            'harkenb2b.myshopify.com',
            BSS_API_KEY
        )

    # Parcours du CSV : pour chaque ligne, on lance une tâche pour chaque couple (client, remise)
    for row in csv_reader:
        product_tag = row[0]  # Le tag produit est dans la première colonne
        discounts = row[1:]   # Les remises se trouvent à partir de la 4ème colonne
        for client_tag, discount in zip(client_tags, discounts):
            # if (client_tag != '6603600'):
            #     continue
            # else:
                print(discount)
                count += 1
                tasks.append(process_discount(product_tag, client_tag, discount, count))

    # Exécute toutes les tâches en parallèle
    await asyncio.gather(*tasks)





if __name__ == "__main__":
    asyncio.run(main())
    sys.exit(0)
