#!/usr/bin/env python3
import xmlrpc.client
import requests
import sys

ODOO_URL = 'http://localhost:16001'
ODOO_DB = 'hazard_new'
ODOO_USER = 'admin'
ODOO_PASS = 'admin'

def main():
    common = xmlrpc.client.ServerProxy(f'{ODOO_URL}/xmlrpc/2/common')
    uid = common.authenticate(ODOO_DB, ODOO_USER, ODOO_PASS, {})
    models = xmlrpc.client.ServerProxy(f'{ODOO_URL}/xmlrpc/2/object')

    print("Obteniendo credenciales de Shopify desde Odoo...")
    config_ids = models.execute_kw(ODOO_DB, uid, ODOO_PASS, 'shopify.config', 'search', [[]])
    if not config_ids:
        print("No se encontró configuración de shopify.")
        return

    config = models.execute_kw(ODOO_DB, uid, ODOO_PASS, 'shopify.config', 'read', [config_ids[0]], {'fields': ['shop_url', 'access_token']})[0]
    
    shop_url = config.get('shop_url')
    access_token = config.get('access_token')

    if not shop_url or not access_token:
        print("Faltan credenciales de Shopify.")
        return

    base_url = f"https://{shop_url}/admin/api/2023-10"
    headers = {
        'X-Shopify-Access-Token': access_token,
        'Content-Type': 'application/json',
    }

    print(f"Conectando a Shopify ({shop_url})... esto puede tomar un poco dependiendo del número de productos.")

    url = f"{base_url}/products.json?limit=250"
    wrong_barcodes = []
    
    while url:
        resp = requests.get(url, headers=headers)
        if resp.status_code != 200:
            print(f"Error consultando Shopify: {resp.status_code} {resp.text}")
            break
        
        data = resp.json()
        products = data.get('products', [])
        
        for p in products:
            for v in p.get('variants', []):
                barcode = v.get('barcode')
                if barcode and not barcode.startswith('200001'):
                    wrong_barcodes.append({
                        'product_title': p.get('title'),
                        'variant_title': v.get('title'),
                        'sku': v.get('sku'),
                        'barcode': barcode,
                        'id': v.get('id')
                    })
        
        # Paginación (Link header)
        link_header = resp.headers.get('Link')
        url = None
        if link_header:
            links = link_header.split(',')
            for link in links:
                if 'rel="next"' in link:
                    url = link[link.find('<')+1 : link.find('>')]
                    break

    print(f"\nSe encontraron {len(wrong_barcodes)} variantes en Shopify con un código de barras que NO empieza con 200001:\n")
    for b in wrong_barcodes:
        print(f"Producto: {b['product_title']} - {b['variant_title']}")
        print(f"SKU: {b['sku']} | Barcode: {b['barcode']} | Variant ID: {b['id']}")

if __name__ == '__main__':
    main()
