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-1vSRJgMe7ItyItmoROu5UXFkHQoq6KDsLeZrjSaeVUt7w-5XIRzsBJVodHXVabjPFdGrN1WPSvxi3Yhj/pub?output=csv"
override_images = fetch_override_data(sheet_url)
print("Override Images Loaded:", override_images)

logging.basicConfig(filename='/var/www/html/indophilia_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 = 'indophiliausa'

# 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
}

# Make a request to the Shopify API using the headers
response = requests.get(endpoint, headers=headers)

# Print the HTTP status code and the API response for debugging
print("HTTP Status Code:", response.status_code)
print("API Response:", response.text)

if response.status_code == 200:
    data = response.json()
    if 'products' in data:
# Create the RSS root and channel
        rss = ET.Element("rss", version="2.0")
        channel = ET.SubElement(rss, "channel")
        ET.SubElement(channel, "title").text = "Indophilia Products"
        ET.SubElement(channel, "link").text = "https://www.indophiliausa.com"
        ET.SubElement(channel, "description").text = "Latest products from Indophilia"
        
        # Process each product
        for item in data['products']:
            for variant in item['variants']:
                product = ET.SubElement(channel, 'item')
                ET.SubElement(product, 'brand').text = "Indophilia"
                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
        
        # Output the XML file
        tree = ET.ElementTree(root)
        tree.write('/var/www/html/indophilia_feed/indophiliausa1.xml', encoding='utf-8', xml_declaration=True)
       
        print("RSS XML file has been created.")
        logging.info('RSS XML file updated successfully.')
    else:
        print("No 'products' key found in data.")
else:
    print("Failed to fetch data. Check the API key and store name.")
