import frappe
from frappe import _

@frappe.whitelist()
def get_qa_ready_serials(limit=50):
    """Get Serial Nos ready for QA."""
    return frappe.get_all('Serial No',
        filters={'r2_status': 'Needs QA'},
        fields=['name', 'item_code', 'item_name', 'pallet', 'cosmetic_grade'],
        limit=limit,
        order_by='creation asc'
    )

@frappe.whitelist()
def create_qa_from_serial(serial_no):
    """Create QA inspection for a Serial No."""
    if not frappe.db.exists('Serial No', serial_no):
        return {'error': 'Serial No not found'}
    
    serial = frappe.get_doc('Serial No', serial_no)
    
    existing = frappe.db.get_value('R2 Device Inspection',
        {'serial_no': serial_no, 'docstatus': ['!=', 2]}, 'name')
    if existing:
        return {'error': f'Inspection {existing} already exists'}
    
    insp = frappe.get_doc({
        'doctype': 'R2 Device Inspection',
        'serial_no': serial_no,
        'item_code': serial.item_code,
        'inspection_date': frappe.utils.today(),
        'inspector': frappe.session.user,
        'cosmetic_grade': serial.cosmetic_grade,
        'screen_condition': serial.screen_condition,
        'keyboard_condition': serial.keyboard_condition,
        'case_condition': serial.case_condition
    })
    insp.insert(ignore_permissions=True)
    
    return {'success': True, 'inspection': insp.name}

@frappe.whitelist()
def auto_grade(serial_no, grade='C5'):
    """Auto-grade a device and move to Priced state."""
    serial = frappe.get_doc('Serial No', serial_no)
    serial.cosmetic_grade = grade
    serial.r2_status = 'Processed'
    serial.save(ignore_permissions=True)
    
    # Apply flat pricing
    item = frappe.db.get_value('Item', serial.item_code, 'item_group')
    flat_prices = {
        'Laptops': {'c3': 250, 'c4': 200, 'c5': 150, 'c6': 100, 'c7': 60, 'c8': 30, 'c9': 15},
        'Desktops': {'c3': 180, 'c4': 150, 'c5': 120, 'c6': 80, 'c7': 50, 'c8': 25, 'c9': 10},
        'Tablets': {'c3': 120, 'c4': 100, 'c5': 80, 'c6': 50, 'c7': 30, 'c8': 15, 'c9': 8},
        'Phones': {'c3': 100, 'c4': 80, 'c5': 60, 'c6': 40, 'c7': 25, 'c8': 12, 'c9': 5}
    }
    prices = flat_prices.get(item, flat_prices['Laptops'])
    price = prices.get(grade.lower(), 100)
    
    serial.suggested_price = price
    serial.assigned_price = price
    serial.pricing_status = 'Priced'
    serial.price_point = grade
    serial.r2_status = 'Priced'
    serial.save(ignore_permissions=True)
    
    return {'success': True, 'price': price}
