import odoo
import json

def create_lab_requests(cr):
    env = odoo.api.Environment(cr, odoo.SUPERUSER_ID, {})
    
    # Delete unwanted demo sale orders
    unwanted_orders = env['sale.order'].search([('name', 'in', ['S00001', 'S00002', 'S00003', 'S00004', 'S00005', 'S00006', 'S00007', 'S00008', 'S00009', 'S00010', 'S00011', 'S00012', 'S00013', 'S00014', 'S00015', 'S00016', 'S00017', 'S00018', 'S00019', 'S00020', 'S00021', 'S00022'])])
    for order in unwanted_orders:
        try:
            order.action_cancel()
        except Exception:
            pass
    try:
        unwanted_orders.unlink()
    except Exception:
        pass

    try:
        # Get patients and doctors - using search instead of ref to be more robust
        patient1 = env['res.partner'].search([('patient_identifier', '=', 'P-A87B01'), ('is_patient', '=', True)], limit=1)
        patient2 = env['res.partner'].search([('patient_identifier', '=', 'P-C45D02'), ('is_patient', '=', True)], limit=1)
        doctor1 = env['res.partner'].search([('doctor_license', '=', 'L-98765'), ('is_doctor', '=', True)], limit=1)
        
        if not patient1:
            print("Warning: Patient 1 not found, skipping lab requests creation")
            return
            
        # Get analysis products - using search instead of ref
        hemograma = env['product.template'].search([('name', '=', 'Hemograma Completo'), ('is_analysis', '=', True)], limit=1)
        perfil_lipidico = env['product.template'].search([('name', '=', 'Perfil Lipídico'), ('is_analysis', '=', True)], limit=1)
        glucosa = env['product.template'].search([('name', '=', 'Glucosa en Sangre'), ('is_analysis', '=', True)], limit=1)
        urocultivo = env['product.template'].search([('name', '=', 'Urocultivo'), ('is_analysis', '=', True)], limit=1)
        
        # Create Lab Request 1 - Multiple analyses with same sample type
        if patient1 and hemograma and perfil_lipidico:
            order1 = env['sale.order'].create({
                'partner_id': patient1.id,
                'doctor_id': doctor1.id if doctor1 else False,
                'is_lab_request': True,
                'order_line': [
                    (0, 0, {'product_id': hemograma.product_variant_id.id, 'product_uom_qty': 1}),
                    (0, 0, {'product_id': perfil_lipidico.product_variant_id.id, 'product_uom_qty': 1})
                ]
            })
            print(f"Created Lab Order 1: {order1.name}")
            
            # Confirm the order to test automatic sample generation
            order1.action_confirm()
            print(f"Confirmed Lab Order 1. Generated samples: {len(order1.generated_sample_ids)}")

        # Create Lab Request 2 - Different sample types
        if patient2 and glucosa and urocultivo:
            order2 = env['sale.order'].create({
                'partner_id': patient2.id,
                'is_lab_request': True,
                'order_line': [
                    (0, 0, {'product_id': glucosa.product_variant_id.id, 'product_uom_qty': 1}),
                    (0, 0, {'product_id': urocultivo.product_variant_id.id, 'product_uom_qty': 1})
                ]
            })
            print(f"Created Lab Order 2: {order2.name}")
            
            # Confirm to test automatic sample generation with different types
            order2.action_confirm()
            print(f"Confirmed Lab Order 2. Generated samples: {len(order2.generated_sample_ids)}")
            
    except Exception as e:
        print(f"Error creating lab requests: {str(e)}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    db_name = 'lims_demo'
    registry = odoo.registry(db_name)
    with registry.cursor() as cr:
        create_lab_requests(cr)
        cr.commit()