
import requests
import json

# Datos de conexión obtenidos de la configuración de Odoo
shop_url = "hazard-mexico.myshopify.com"
token = "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"
headers = {'X-Shopify-Access-Token': token}

# SKU a investigar
sku_to_check = "HRS-POL-BLUKNT-M-WHT-S"

print(f"--- INVESTIGACIÓN DE STOCK PARA SKU: {sku_to_check} ---")

# 1. Obtener ubicaciones para ver qué tenemos configurado en Shopify
loc_url = f"https://{shop_url}/admin/api/2024-01/locations.json"
r_loc = requests.get(loc_url, headers=headers)
print(f"Status Ubicaciones: {r_loc.status_code}")
locations = r_loc.json().get('locations', [])
for l in locations:
    print(f"Ubicación: {l['name']} (ID: {l['id']})")

# 2. Buscar el producto por SKU usando GraphQL (más directo)
query = """
{
  productVariants(first: 1, query: "sku:%s") {
    edges {
      node {
        id
        legacyResourceId
        inventoryItem {
          id
          legacyResourceId
          inventoryLevels(first: 10) {
            edges {
              node {
                quantities(names: ["available"]) {
                  name
                  quantity
                }
                location {
                  id
                  name
                }
              }
            }
          }
        }
      }
    }
  }
}
""" % sku_to_check

gql_url = f"https://{shop_url}/admin/api/2024-01/graphql.json"
r_gql = requests.post(gql_url, headers=headers, json={'query': query})

if r_gql.status_code == 200:
    data = r_gql.json()
    variants = data.get('data', {}).get('productVariants', {}).get('edges', [])
    if not variants:
        print(f"\nNo se encontró ninguna variante con SKU {sku_to_check} via GraphQL.")
    else:
        var_node = variants[0]['node']
        inv_item = var_node['inventoryItem']
        print(f"\nVariante encontrada en Shopify!")
        print(f"Variant ID: {var_node['legacyResourceId']}")
        print(f"Inventory Item ID: {inv_item['legacyResourceId']}")
        
        print("\nNiveles de inventario reportados por la API:")
        for edge in inv_item['inventoryLevels']['edges']:
            loc = edge['node']['location']
            qties = edge['node']['quantities']
            qty = qties[0]['quantity'] if qties else 0
            print(f"- {loc['name']} (ID: {loc['id'].split('/')[-1]}): {qty}")
else:
    print(f"Error en GraphQL: {r_gql.status_code} - {r_gql.text}")
