import frappe
from frappe import _

def validate_hardware_tests(doc, method):
    """Before save: if CPU or RAM test failed, route to Dismantle."""
    
    # Check if this is a device-type serial (has item_code)
    if not doc.item_code:
        return
    
    # Check CPU and RAM test results
    cpu_fail = doc.get("cpu_test") == "Fail"
    ram_fail = doc.get("ram_test") == "Fail"
    
    if cpu_fail or ram_fail:
        # Set grade to Flagged
        doc.grade = "Flagged"
        doc.pricing_status = "Dismantle"
        doc.assigned_price = None
        
        # Route to Dismantle warehouse if it exists
        dismantle_wh = frappe.db.exists("Warehouse", "Dismantle - WR")
        if dismantle_wh:
            doc.warehouse = "Dismantle - WR"
        
        # Log the failure reason
        reasons = []
        if cpu_fail:
            reasons.append("CPU test failed")
        if ram_fail:
            reasons.append("RAM test failed")
        
        frappe.msgprint(
            _("Hardware failure detected: {0}. Device routed to Dismantle.").format(", ".join(reasons)),
            indicator="red",
            alert=True
        )
