import xmlrpc.client
import sys

url = 'http://localhost:16001'
db = 'hazard_new'
username = 'admin'
password = '123'

try:
    common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url))
    uid = common.authenticate(db, username, 'admin', {})
    if not uid:
        uid = common.authenticate(db, 'admin', '123', {})
    
    models = xmlrpc.client.ServerProxy('{}/xmlrpc/2/object'.format(url))
    
    ref = 'HRS-GLV-CABRET-U-WHT-L'
    products = models.execute_kw(db, uid, 'admin', 'product.product', 'search_read', 
                                 [[['default_code', '=', ref]]], 
                                 {'fields': ['id', 'name', 'display_name', 'product_tmpl_id', 'active']})
    
    if not products:
        print(f"Producto {ref} no encontrado.")
        sys.exit()
        
    print(f"--- SE ENCONTRARON {len(products)} PRODUCTOS CON ESE SKU ---")
    for product in products:
        tmpl_id = product['product_tmpl_id'][0]
        print(f"\nVariante ID: {product['id']} | Activo: {product['active']}")
        print(f"Name (variante): {product['name']}")
        print(f"Display Name: {product['display_name']}")
        
        tmpls = models.execute_kw(db, uid, 'admin', 'product.template', 'read', 
                                  [[tmpl_id]], 
                                  {'fields': ['id', 'name', 'active']})
        print(f"Template Name: {tmpls[0]['name']} | Activo: {tmpls[0]['active']}")
        
        # 3. Buscar las órdenes más recientes de este producto
        print("   --- ULTIMAS LINEAS DE VENTA ---")
        sols = models.execute_kw(db, uid, 'admin', 'sale.order.line', 'search_read', 
                                 [[['product_id', '=', product['id']]]], 
                                 {'fields': ['id', 'order_id', 'name', 'create_date'], 'limit': 3, 'order': 'id desc'})
        for sol in sols:
            print(f"   SOL ID: {sol['id']} | Fecha: {sol['create_date']} | Pedido: {sol['order_id'][1]} | Descripcion: {sol['name']}")
            
        print("   --- ULTIMOS MOVIMIENTOS DE INVENTARIO ---")
        moves = models.execute_kw(db, uid, 'admin', 'stock.move', 'search_read', 
                                  [[['product_id', '=', product['id']]]], 
                                  {'fields': ['id', 'picking_id', 'name', 'description_picking', 'create_date'], 'limit': 3, 'order': 'id desc'})
        for m in moves:
            picking_name = m['picking_id'][1] if m['picking_id'] else 'Sin Albaran'
            print(f"   Move ID: {m['id']} | Fecha: {m['create_date']} | Albaran: {picking_name} | Desc: {m['description_picking']}")

except Exception as e:
    print("Error conectando o consultando Odoo:", e)
