import requests
import xml.etree.ElementTree as ET
import logging
import csv

# Function to fetch and parse override data from Google Sheets
def fetch_override_data(sheet_url):
    response = requests.get(sheet_url)
    reader = csv.reader(response.text.strip().split('\n'))
    override_dict = {rows[0]: rows[1] for rows in reader if len(rows) >= 2}
    return override_dict

# URL of your published Google Sheet
sheet_url = "https://docs.google.com/spreadsheets/d/e/2PACX-1vSrKlT3Ir6DS19wF6LNqe1wYzoHjHOnsLXAJ9YQmjksAxH9izaU3dT1FXrtBtjOhCimy1ohbXgdVmgz/pub?output=csv"
override_images = fetch_override_data(sheet_url)
print("Override Images Loaded:", override_images)

logging.basicConfig(filename='/var/www/html/wintage_feed/script.log', level=logging.INFO, format='%(asctime)s:%(levelname)s:%(message)s')
logging.info('Script started running.')

# Set up your Admin API Access Token and your store name
access_token = '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'
store_name = 'wintage-usa'

# Set up the endpoint with your store name
endpoint = f'https://{store_name}.myshopify.com/admin/api/2022-04/products.json'

# Set up the headers with your access token
headers = {
    'Content-Type': 'application/json',
    'X-Shopify-Access-Token': access_token
}

# Pagination setup
url = endpoint

# Create the RSS root and channel
rss = ET.Element("rss", version="2.0")
channel = ET.SubElement(rss, "channel")
ET.SubElement(channel, "title").text = "Wintage Products"
ET.SubElement(channel, "link").text = "https://wintagefashion.com/"
ET.SubElement(channel, "description").text = "Latest products from Wintage"

# Loop to handle pagination
while url:
    response = requests.get(url, headers=headers)
    print("HTTP Status Code:", response.status_code)
    if response.status_code == 200:
        data = response.json()        
        # Process each product
        for item in data['products']:
            for variant in item['variants']:
                product = ET.SubElement(channel, 'item')
                ET.SubElement(product, 'brand').text = "Wintage"
                ET.SubElement(product, 'id').text = str(variant['id'])
                
                # Apply image override if available
                item_group_id = str(item['id'])  # Convert item ID to string for dictionary lookup
                primary_image_link = override_images.get(item_group_id, item['images'][0]['src'] if item['images'] else "No image available")
                ET.SubElement(product, 'image_link').text = primary_image_link
                
                # Determine availability based on inventory data
                if variant.get('inventory_quantity', 0) > 0 or variant.get('inventory_policy', '') == 'continue':
                    availability = "in stock"
                else:
                    availability = "out of stock"
                ET.SubElement(product, 'availability').text = availability
                ET.SubElement(product, 'condition').text = "new"  # Assuming all items are new
                ET.SubElement(product, 'price').text = str(variant['price'])
                ET.SubElement(product, 'link').text = f"https://{store_name}.myshopify.com/products/{item['handle']}?variant={variant['id']}"
                ET.SubElement(product, 'item_group_id').text = str(item['id'])
                ET.SubElement(product, 'product_type').text = item['product_type']
                ET.SubElement(product, 'google_product_category').text = item['product_type']
                ET.SubElement(product, 'mpn').text = variant['sku']
                ET.SubElement(product, 'title').text = item['title']
                ET.SubElement(product, 'description').text = item['body_html'].replace('<br>', ' ')
                
                # Handle additional images
                if len(item['images']) > 1:
                    additional_images = ','.join([img['src'] for img in item['images'][1:]])
                    ET.SubElement(product, 'additional_image_link').text = additional_images
        # Prepare for the next page if it exists
        next_page_link = response.links.get('next', {}).get('url') if 'next' in response.links else None
        url = next_page_link
    else:
        print("Failed to fetch data:", response.text)
        break        



# Output the XML file
tree = ET.ElementTree(rss)
tree.write('/var/www/html/indophilia_feed/wintageusa.xml', encoding='utf-8', xml_declaration=True)
logging.info('RSS XML file updated successfully.')
print("RSS XML file has been created.")
