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

# 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
from Harken.Tarifs.utils import find_existing_customer, find_rule_by_name, find_existing_product
from Harken.files.CSV_Converter.txt_to_csv import convert_txt_to_csv
from Harken.FTP.Utils import download_huggy_tarifs_files_txt
from Harken.API.get_all_customers import get_all_customers
from Harken.API.tokens import access_tokens
from Harken.API.get_all_products import get_all_products

PRODUCTS_FILE_PATH_JSON = '../Products/products.json'
CUSTOMERS_FILE_PATH_JSON = '../Customers/Customers.json'
FILE_PATH_CSV = '../files/Tarifs/tarifsParticuliers.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():

    products = await get_all_products(access_tokens, SHOP_NAME, "2024-10")
    download_huggy_tarifs_files_txt()
    convert_txt_to_csv('tarifsParticuliers.txt', '../files/Tarifs/tarifsParticuliers.csv')
    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", [])]
        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='ISO-8859-1') as afile:
        content = await afile.read()
        lines = [line.strip().strip('"') for line in content.splitlines() if line.strip()]
        csvfile = io.StringIO("\n".join(lines))
        csv_reader = csv.reader(csvfile, delimiter=';')
        count = 0
        for row in csv_reader:
            product_sku = row[16]
            customer_ref = row[10]
            # Si la ligne ne contient aucun champ, on passe à la suivante
            if not row:
                continue
            # On ne traite que les lignes dont la première donnée est "GENERAL" et la dernière "P"
            if row[0] != "GENERAL" or row[-1] != "P":
                continue
            # elif customer_ref != "5603308":
            #     continue
            else:
                customer_tag = 'Code Client : ' + customer_ref
                custmer = find_existing_customer(customers, customer_ref)
                product = find_existing_product(products, product_sku)
                price_to_apply = row[-2]
                price_to_apply = price_to_apply.replace(',', '.')
                price_to_apply = round(float(price_to_apply), 2)
                print(product_sku)
                print(customer_ref)
                print(price_to_apply)
                if custmer:
                    if product :
                        customer_id = custmer.get('id')
                        rule_name = f"Individual --- Client(s): {customer_id} --- Produit(s): {product} --- Remise: {price_to_apply}"
                        founded_rule = find_rule_by_name(rule_name, all_cp_rules)
                        rule_id = founded_rule['id'] if founded_rule else None

                        tasks.append(
                            asyncio.to_thread(
                                create_or_update_rule,
                                0,
                                4,
                                4,
                                rule_name,
                                customer_tag,
                                product,
                                customer_id,
                                price_to_apply,
                                rule_id,
                                'harkenb2b.myshopify.com',
                                BSS_API_KEY,
                                0,
                                product
                            )
                        )
    if tasks:
        await asyncio.gather(*tasks)


print("✅ Toutes les règles ont été traitées.")


# Traitez ici la ligne valide


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

