import requests
import xml.etree.ElementTree as ET
from xml.sax.saxutils import escape

# Configuration API Shopify
ACCESS_TOKEN = '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'
SHOP_NAME = '0a1f4e-3.myshopify.com'
API_VERSION = '2023-01'

def get_all_translated_products(lang_code='fr'):
    url = f"https://{SHOP_NAME}/admin/api/{API_VERSION}/graphql.json"
    headers = {
        "Content-Type": "application/json",
        "X-Shopify-Access-Token": ACCESS_TOKEN
    }
    products = []
    has_next_page = True
    cursor = None
    while has_next_page:
        query = '''
        {
          products(first: 250 %s) {
            edges {
              node {
                id
                title
                handle
                description
                vendor
                variants(first: 1) {
                  edges {
                    node {
                      price
                      sku
                      inventoryQuantity
                    }
                  }
                }
                images(first: 1) {
                  edges {
                    node {
                      src
                    }
                  }
                }
                translations(locale: "%s") {
                  key
                  value
                }
              }
            }
            pageInfo {
              hasNextPage
              endCursor
            }
          }
        }
        ''' % (f', after: "{cursor}"' if cursor else '', lang_code)
        response = requests.post(url, json={"query": query}, headers=headers)
        if response.status_code == 200:
            response_json = response.json()
            product_edges = response_json['data']['products']['edges']
            products.extend(product_edges)
            page_info = response_json['data']['products']['pageInfo']
            has_next_page = page_info['hasNextPage']
            cursor = page_info['endCursor'] if has_next_page else None
        else:
            print(f"Error: {response.status_code} - {response.text}")
            break
    return products

def create_xml_feed(products, domain):
    feed = ET.Element("feed", xmlns="http://www.w3.org/2005/Atom", xmlns_g="http://base.google.com/ns/1.0")
    title = ET.SubElement(feed, "title")
    title.text = f"Produit-Feed pour {domain}"
    link = ET.SubElement(feed, "link", href=f"https://{domain}")
    updated = ET.SubElement(feed, "updated")
    updated.text = "2024-01-01T00:00:00Z"

    for product in products:
        product_node = product['node']
        entry = ET.SubElement(feed, "entry")
        g_id = ET.SubElement(entry, "{http://base.google.com/ns/1.0}id")
        g_id.text = product_node['id']
        title_es = next((t['value'] for t in product_node['translations'] if t['key'] == 'title'), product_node['title'])
        description_es = next((t['value'] for t in product_node['translations'] if t['key'] == 'body_html'), product_node['description'])
        title = ET.SubElement(entry, "title")
        title.text = escape(title_es)
        summary = ET.SubElement(entry, "summary")
        summary.text = escape(description_es[:200])
        link = ET.SubElement(entry, "link", href=f"https://{domain}/products/{product_node['handle']}")
        image_link = ET.SubElement(entry, "{http://base.google.com/ns/1.0}image_link")
        image_link.text = product_node['images']['edges'][0]['node']['src'] if product_node['images']['edges'] else ''
        price = ET.SubElement(entry, "{http://base.google.com/ns/1.0}price")
        price.text = f"{product_node['variants']['edges'][0]['node']['price']} EUR"
        availability = ET.SubElement(entry, "{http://base.google.com/ns/1.0}availability")
        inventory_quantity = 10  # Utilisation de la valeur fixe pour l'inventaire
        availability.text = "in stock" if inventory_quantity > 0 else "out of stock"
        brand = ET.SubElement(entry, "{http://base.google.com/ns/1.0}brand")
        brand.text = "Aesthetic Posters"  # Nom de la marque
        condition = ET.SubElement(entry, "{http://base.google.com/ns/1.0}condition")
        condition.text = "new"
        google_category = ET.SubElement(entry, "{http://base.google.com/ns/1.0}google_product_category")
        google_category.text = "682" 
    return ET.ElementTree(feed)

# Adaptation des variables pour l'Espagne
products = get_all_translated_products('es')
domain = 'aesthetic-posters.es'
xml_feed = create_xml_feed(products, domain)
xml_feed.write("product_feed_es.xml", encoding='utf-8', xml_declaration=True)
print(f"XML feed for {domain} saved as product_feed_es.xml")

