import requests
import base64
import time
from api import create_category

# ✅ 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")

image_id = 675
# ✅ URL de l'API WordPress pour téléverser une image
media_api_url = f"https://lescreationsdemissbleue.local/wp-json/wp/v2/media/{image_id}"

# ✅ Fichier image à uploader
image_path = "C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\pyramide_olfactive.png"  
image_name = "pyramide_olfactive.png"

images_to_upload = [
    ("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\Photos_bougies_Claudine\\Bougies\\Chope\\chope-sapin-face.jpg", "chope-sapin-face.jpg"),
    ("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\Photos_bougies_Claudine\\Bougies\\Chope\\chope-adoucissant-face.jpg", "chope-adoucissant-face.jpg")
]

# ✅ Headers avec l'authentification correcte
"""headers = {
    "Authorization": f"Basic {auth_base64}",
    "Content-Disposition": f"attachment; filename={image_name}"
}"""

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

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
    )

# ✅ Lecture et envoi du fichier
"""with open(image_path, "rb") as image_file:
    response = requests.post(
        media_api_url,
        headers=headers,
        files={"file": image_file},
        verify=False  # ⚠️ Désactiver la vérification SSL si problème de certificat
    )"""

# ✅ Vérifier la réponse
if response.status_code == 201:
    media_data = response.json()
    image_id = media_data["id"]
    image_url = media_data["source_url"]
    print(f"✅ Image téléversée avec succès ! ID : {image_id}, URL : {image_url}")
else:
    print(f"❌ Erreur lors du téléversement de l'image : {response.status_code}")
    print(response.text)  # 🔍 Afficher l'erreur détaillée


"""def create_image(name, description, source):
    images_data = {
        "name": name,
        "description": description,
        "source": source
    }

    response = requests.post(media_api_url, headers=headers, json=images_data)

    if response.status_code == 201:
        category = response.json()
        print(f"✅ Catégorie '{name}' créée avec succès ! ID : {category['id']}")
        return category["id"]
    else:
        print(f"❌ Erreur lors de la création de '{name}' : {response.status_code} {response.text}")
        return None"""
    
categories_api_url = "https://lescreationsdemissbleue.local/wp-json/wp/v2/product_cat"

    
def upload_image(image_path, image_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()
        print(f"✅ Image téléversée : {media_data['source_url']}")
        category_parent_id = create_category("Gamme prestige", "Catégorie principale pour organiser la gamme prestige", media_data["id"])
        if category_parent_id:
            subcategory_id = create_category("Chopes", "Sous-catégorie de la gamme prestige", category_parent_id, media_data["id"])
            return media_data["id"]  # Retourne l'ID de l'image
    else:
        print(f"❌ Erreur image : {response.status_code} {response.text}")
        return None

# ✅ Boucle sur les images et envoi
uploaded_images = []
for image_path, image_name in images_to_upload:
    image_id = upload_image(image_path, image_name)
    print('iciiiiiiiiiiiii')
    if image_id:
        uploaded_images.append(image_id)
    time.sleep(2)  # ⏳ Pause pour éviter la surcharge du serveur

# ✅ Liste des images téléversées avec leur ID
print(f"📌 Images téléversées : {uploaded_images}")