#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script para confirmar la orden S00027
"""

import odoo

def confirm_order(cr):
    """Confirmar la orden S00027"""
    env = odoo.api.Environment(cr, odoo.SUPERUSER_ID, {})
    
    # Buscar la orden S00027
    order = env['sale.order'].search([('name', '=', 'S00027')], limit=1)
    if not order:
        print("❌ No se encontró la orden S00027")
        return
    
    print(f"✓ Orden encontrada: {order.name}")
    print(f"  Cliente: {order.partner_id.name}")
    print(f"  Estado actual: {order.state}")
    print(f"  Líneas de orden: {len(order.order_line)}")
    
    for line in order.order_line:
        print(f"    - {line.product_id.name} (cant: {line.product_uom_qty})")
    
    if order.state == 'sale':
        print("\n✓ La orden ya está confirmada")
        print(f"  Muestras generadas: {len(order.generated_sample_ids)}")
        for sample in order.generated_sample_ids:
            print(f"    - {sample.name}: {sample.sample_state}")
        
        # Ver las pruebas generadas
        tests = env['lims.test'].search([
            ('sale_order_line_id.order_id', '=', order.id)
        ])
        print(f"\n  Pruebas de laboratorio: {len(tests)}")
        for test in tests:
            print(f"    - {test.name}: {test.product_id.name} ({test.state})")
            if test.result_ids:
                print(f"      Resultados: {len(test.result_ids)}")
                for result in test.result_ids[:3]:  # Mostrar solo los primeros 3
                    print(f"        - {result.parameter_id.name} ({result.parameter_value_type})")
    else:
        print("\n🔄 Confirmando orden...")
        try:
            order.action_confirm()
            print("✅ ¡Orden confirmada exitosamente!")
            print(f"  Nuevo estado: {order.state}")
            print(f"  Muestras generadas: {len(order.generated_sample_ids)}")
            
            # Verificar las pruebas generadas
            tests = env['lims.test'].search([
                ('sale_order_line_id.order_id', '=', order.id)
            ])
            print(f"  Pruebas generadas: {len(tests)}")
            for test in tests:
                print(f"    - {test.name}: {test.product_id.name}")
                
        except Exception as e:
            print(f"❌ Error al confirmar: {str(e)}")
            import traceback
            traceback.print_exc()

if __name__ == '__main__':
    db_name = 'lims_demo'
    try:
        registry = odoo.modules.registry.Registry(db_name)
        with registry.cursor() as cr:
            confirm_order(cr)
            cr.commit()
            print("\n✅ Transacción completada")
    except Exception as e:
        print(f"\n❌ Error: {e}")
        import traceback
        traceback.print_exc()