from woocommerce import API
import pandas as pd
import ezodf
import requests
import pprint
import base64
import time
import json

wcapi = API(
    url="https://lescreationsdemissbleue.local",
    consumer_key="ck_604e9b7b5d290cce72346efade6b31cb9a1ff28e",
    consumer_secret="cs_563974c7e59532c1ae1d0f8bbf61f0500d6bc768",
    wp_api=True,
    version="wc/v3",
    verify_ssl=False # Désactive la vérification SSL pour le développement
)

# ✅ Identifiants WordPress (et non WooCommerce)
wordpress_username = "admin_lcdm"  # Remplace par ton username WordPress
wordpress_application_password = "yTW8 Mc6J FUCN tPSq bnuJ 0Sdw" #"#8io_mb!55@Bis"  # Généré dans WordPress > Utilisateurs

# ✅ Générer l'authentification Basic en base64
auth_str = f"{wordpress_username}:{wordpress_application_password}"
auth_bytes = auth_str.encode("utf-8")
auth_base64 = base64.b64encode(auth_bytes).decode("utf-8")

images_to_upload = [
    {'categories': [
        ("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\Photos_Claudine\\Photos_bougies_Claudine\\Bougies\\Chope\\chope-sapin-face.jpg", "chope-sapin-face.jpg", "Chope sapin", "Chope sapin de face", "Gamme prestige"),
        ("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\Photos_Claudine\\Photos_bougies_Claudine\\Bougies\\Chope\\chope-adoucissant-face.jpg", "chope-adoucissant-face.jpg", "Chope adoucissant", "Chope adoucissant de face", "Chopes"),
        ]
    },
    {'images':[
        ("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\Photos_Claudine\\Photos_bougies_Claudine\\Bougies\\Chope\\chope-citron-meringue-face.jpg", "chope-citron-meringue-face.jpg", "Chope citron meringuée (1)", "Chope citron meringuée de face", "Chopes"),
        ("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\Photos_Claudine\\Photos_bougies_Claudine\\Bougies\\Chope\\chope-citron-meringue-haut.jpg", "chope-citron-meringue-haut.jpg", "Chope citron meringuée (2)", "Chope citron meringuée de haut", "Chopes"),
        ("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\Photos_Claudine\\Photos_bougies_Claudine\\Bougies\\Chope\\chope-citron-meringue-dos.jpg", "chope-citron-meringue-dos.jpg", "Chope citron meringuée (3)", "Chope citron meringuée de dos", "Chopes")
        ]
    }
]
"""updata_data = {
    "title" : "Pyramide olfactive test",
    "alt_text": "Pyramide olfactive test"
}

response = requests.post(
        media_api_url,
        headers=headers,
        json=updata_data,
        verify=False  # ⚠️ Désactiver la vérification SSL si problème de certificat
    )"""


def update_data(title, alt, image_id):
    updata_data = {
            "title" : title,
            "alt_text": alt
        }
    headers = {
        "Authorization": f"Basic {auth_base64}",
        "Content-Type": "application/json"
    }
    
    response = requests.post(
        f"{media_api_url}/{image_id}",
        headers=headers,
        json=updata_data,
        verify=False  # ⚠️ Désactiver la vérification SSL si problème de certificat
    )
      # ✅ Vérifier la réponse
    if response.status_code == 200:
        print(f"✅ Métadonnées mises à jour pour l’image {image_id} : {title} | ALT : {alt}")
        return response.json()  # Retourne les nouvelles données de l'image
    else:
        print(f"❌ Erreur mise à jour image : {response.status_code} {response.text}")
        return None

media_api_url = f"https://lescreationsdemissbleue.local/wp-json/wp/v2/media"

def upload_image(image_path, image_name, title, alt, category_name):
    with open(image_path, "rb") as image_file:
        response = requests.post(
            media_api_url,
            headers={
                "Authorization": f"Basic {auth_base64}",
                "Content-Disposition": f"attachment; filename={image_name}"
            },
            files={"file": image_file},
            verify=False
        )
        
    if response.status_code == 201:
        media_data = response.json()
        update_data(title, alt, media_data["id"])   
        return {'category_name':category_name, 'id':media_data["id"], 'image_name':image_name}  # Retourne l'ID de l'image
    else:
        print(f"❌ Erreur image : {response.status_code} {response.text}")
        return None
    
categories_api_url = "https://lescreationsdemissbleue.local/wp-json/wp/v2/product_cat"
category_parent_id = 0
image_id= None
categories_to_create  = [
    ("Gamme prestige", "Catégorie principale pour organiser la gamme prestige", None),
    ("Chopes", "Catégorie enfant de la gamme prestige", category_parent_id),
]

def create_category(name, description, parent_id=None):
    """Crée une catégorie WooCommerce (principale ou sous-catégorie)"""
    category_data = {
        "name": name,
        "description": description,
        "parent": parent_id if parent_id else 0, 
        #'images':image_id
    }   
    response = wcapi.post("products/categories/", category_data)

    print(f"response.status_code = {response.status_code}")
    print(f"Réponse API = {response.text}")
    if response.status_code == 201:
        category = response.json()
        #pprint.pprint(category)
        #return category["id"]
        return category
    else:
        return None

uploaded_images_cat = []    
for image_path, image_name, title, alt, category_name in images_to_upload[0]['categories']:
    category_dict = upload_image(image_path, image_name, title, alt, category_name)
    uploaded_images_cat.append(category_dict)
        
for image_path, image_name, title, alt, category_name in images_to_upload[1]['images']:
    upload_image(image_path, image_name, title, alt, category_name)
  
 
def get_id_img_for_category(category):
    headers = {
        "Authorization": f"Basic {auth_base64}",
        "Content-Type": "application/json"
    }

    response = requests.get(
            media_api_url,
            headers=headers,
            verify=False  # ⚠️ Désactiver la vérification SSL si problème de certificat
        )
    response_images = response.json()
    image_id = {}
    for img in response_images:
        for cat_img in uploaded_images_cat:
                print(f"cat_img['id'] = {cat_img['id']}")
                if category['name'] == cat_img['category_name']:            
                    image_id = {'id':cat_img['id']}
                    break
    print(f"image_id = {image_id}")
    return image_id
    
    
def update_data_img_id_for_category(img_id, cat_id):
    update_category_data = {
            "image" : img_id,
        }
    print(f"cat_id = {cat_id}")
    print(f"img_id = {img_id}")
    response = wcapi.put(f"products/categories/{cat_id}", update_category_data)
"""def get_id_img_for_category(category):
    category_list_by_doc = [cat.strip().replace('"', '') for cat in product['Categorie'].split("/")]
    #list_images_by_doc = [img.strip().replace('"', '') for img in product['Photo'].split(",")]
    #print(f'category_list_by_doc = {category_list_by_doc}')

    headers = {
        "Authorization": f"Basic {auth_base64}",
        "Content-Type": "application/json"
    }

    response = requests.get(
            media_api_url,
            headers=headers,
            verify=False  # ⚠️ Désactiver la vérification SSL si problème de certificat
        )

    response_images = response.json()
    #print(f"response_images = {type(response_images)}")
    for img in response_images:
        #print(f"type_img = {type(img)}")
        for key, value in img.items():
            if key == 'source_url':
                #print(f"key= {key}, value = {value}")
                for image in list_images_by_doc:
                    if category['image_name'] in value:
                        img_id = category['id']
    #pprint.pprint(f'list_image_for_product = {list_image_for_product}')
    return img_id"""

for category in categories_to_create:
    name, description, parent_id = category
    if parent_id != None:
        parent_id = cat['id']
    #img_id = get_id_img_for_category(category)
    cat = create_category(name, description, parent_id)
    img_id = get_id_img_for_category(cat)
    update_data_img_id_for_category(img_id,cat["id"])

def get_list_id_img_for_product(product):
    list_images_by_doc = [img.strip().replace('"', '') for img in product['Photo'].split(",")]

    headers = {
        "Authorization": f"Basic {auth_base64}",
        "Content-Type": "application/json"
    }

    response = requests.get(
            media_api_url,
            headers=headers,
            verify=False  # ⚠️ Désactiver la vérification SSL si problème de certificat
        )

    list_image_for_product = []
    response_images = response.json()
    for img in response_images:
        for key, value in img.items():
            if key == 'source_url':
                for image in list_images_by_doc:
                    if image in value:
                        img_id_for_product = {'id':img['id'], 'value':value}
                        list_image_for_product.append(img_id_for_product)
                        break
    return list_image_for_product[::-1]
                            

def get_list_category_for_product(product):
    response = wcapi.get("products/categories")
    category_list_by_doc = [cat.strip().replace('"', '') for cat in product['Categorie'].split("/")]
    list_category_for_product = []
    for category in response.json():
        for cat in category_list_by_doc:
            if category['name'] == cat:
                id_category = {'id':category['id']}
                list_category_for_product.append(id_category)
    return list_category_for_product

def update_data_list_cat_product(list_category_id, list_img_id, product_id):
    product_data = {
        'categories':list_category_id,
        'images':list_img_id,
    }
    wcapi.put(f"products/{product_id}", product_data)
    response_product =  wcapi.get(f"products/{product_id}")

def create_product(product):
    
    product_data = {
        'name' : product['Nom'],
        'price': product['Prix'],
        'stock_quantity': product['Stock'],
        'description': product['Description'],
        #'images':list_id_image,
        'short_description':product['Courte_description'],
        #'categories':list_id_category
    }
    response = wcapi.post("products/", product_data)

    print(f"response.status_code = {response.status_code}")
    print("Réponse API :", response.text)
    if response.status_code == 201:
        product = response.json()
        return product["id"]
    else:
        return None

ezodf.config.set_table_expand_strategy('all')
doc = ezodf.opendoc("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\infos_site.ods")

# Sélectionner la première feuille
sheet = doc.sheets[0]

# Convertir la feuille en DataFrame
data = []
for row in sheet.rows():
    data.append([cell.value for cell in row])

# Convertir en DataFrame Pandas
df = pd.DataFrame(data)
df.columns = df.iloc[0]
df = df[1:].reset_index(drop=True)
df = df.dropna(how='all')
json_data = df.to_dict(orient="records")
#get_data = json.dumps(json_data, indent=4, ensure_ascii=False)
for product in json_data:
    #list_img_id = get_list_id_img_for_product(product)
    product_id = create_product(product)  
    list_category_id = get_list_category_for_product(product)
    list_img_id = get_list_id_img_for_product(product)
    update_data_list_cat_product(list_category_id, list_img_id, product_id)
"""
categories_to_create  = [
    ("Gamme prestige", "Catégorie principale pour organiser la gamme prestige", image_id, None),
    ("Chope", "Catégorie enfant de la gamme prestige", image_id, category_parent_id),
]

uploaded_images_cat = []
for image_path, image_name, title, alt, category_name in images_to_upload[0]['categories']:
    image_name_id = upload_image(image_path, image_name, title, alt, category_name)
    if image_name_id:
        uploaded_images_cat.append(image_name_id)
        
uploaded_images = []
for image_path, image_name, title, alt, category_name in images_to_upload[1]['images']:
    
    print(f'image_name = {image_name}')
    image_name_id = upload_image(image_path, image_name, title, alt, category_name)
    if image_name_id:
        uploaded_images.append(image_name_id)
    print(f"uploaded_images = {uploaded_images}")

def create_category(name, description, image_id=None, parent_id=None):
    category_data = {
        "name": name,
        "description": description,
        "parent": parent_id if parent_id else 0, 
    }
    if image_id:
        category_data['image'] = {'id':image_id}
    

    #response = requests.post(categories_api_url, headers=headers, json=category_data, verify=False)
    response = wcapi.post("products/categories/", category_data)

    print(f"response.status_code = {response.status_code}")
    print(f"Réponse API = {response.text}")
    if response.status_code == 201:
        category = response.json()
        #pprint.pprint(category)
        #return category["id"]
        return {'category_name':category_name, 'id':category["id"]}
    else:
        return None

categories_list = [] 
for category in categories_to_create:
    name, description, image_id, parent_id = category
    for image in uploaded_images_cat:
        if image['category_name'] == name:
            image_id = image['id']
            if parent_id != None:
                parent_id = cat['id']
            cat = create_category(name, description, image_id, parent_id)
            print(f"category = {category}")
            print(type(category))
            categories_list.append(cat)
            """  
"""list_id_image = []
    pprint.pprint(uploaded_images)
    for image in uploaded_images:
        if image['image_name'] in image_list:
            image = {'id':image['id']}
            list_id_image.append(image)
            
    list_id_category = []
    pprint.pprint(categories_list)
    pprint.pprint(category_list)
    print('______')
    for category in categories_list:
        print(f'categoryyyy = {category}')
        if category['category_name'] in category_list:
            print(f"category['id'] = {category['id']}")
            cat = {'id':category['id']}
            list_id_category.append(cat)
    print(f"list_id_category = {list_id_category}") 
    
    list_test = []
    test = {'id':3}
    list_test.append(test) 
    print(f"list_test = {list_test}")  """  
    