import math

REBAR_WEIGHTS = {
    6: 0.222, 8: 0.395, 10: 0.617, 12: 0.888, 16: 1.58, 20: 2.47,
    25: 3.85, 28: 4.83, 32: 6.31, 36: 7.99,
}

def solve_reinforcement_qty(inputs):
    try:
        members = inputs.get('members', [])
        wastage = inputs.get('wastage', 5)
        # Handle if wastage is passed as string '5' or number 5
        try:
             wastagePct = float(wastage) / 100
        except:
             wastagePct = 0.05

        if not isinstance(members, list) or len(members) == 0:
            return {'error': 'No members provided'}

        totalWeight = 0
        diaBreakdown = {}
        memberResults = []

        for m in members:
            count = float(m.get('count', 0))
            dia = int(m.get('dia', 0)) # assuming integer dia keys
            noOfBars = float(m.get('noOfBars', 0))
            length = float(m.get('length', 0)) 
            
            unitWt = REBAR_WEIGHTS.get(dia, 0)
            mainWt = count * noOfBars * length * unitWt

            stirrupWt = 0
            if m.get('hasStirrups'):
                memberLen = float(m.get('memberLength', 0))
                stirSpacing = float(m.get('stirrupSpacing', 200))
                stirDia = int(m.get('stirrupDia', 8))

                if memberLen > 0 and stirSpacing > 0:
                     stirCount = math.ceil((memberLen * 1000) / stirSpacing) + 1
                     stirLen = 1.2 # m
                     stirUnitWt = REBAR_WEIGHTS.get(stirDia, 0)
                     stirrupWt = count * stirCount * stirLen * stirUnitWt
                     
                     diaBreakdown[stirDia] = diaBreakdown.get(stirDia, 0) + stirrupWt

            total = mainWt + stirrupWt
            totalWeight += total

            diaBreakdown[dia] = diaBreakdown.get(dia, 0) + mainWt

            m_res = m.copy()
            m_res['mainWt'] = mainWt
            m_res['stirrupWt'] = stirrupWt
            m_res['total'] = total
            memberResults.append(m_res)

        withWastage = totalWeight * (1 + wastagePct)

        # Format diaBreakdown for response
        diaData = []
        for d, wt in diaBreakdown.items():
             diaData.append({'dia': f'φ{d}', 'weight': float(f'{wt:.1f}')})
        
        # Sort by diameter
        diaData.sort(key=lambda x: int(x['dia'][1:]))

        return {
            'result': {
                'memberResults': memberResults,
                'totalWeight': totalWeight,
                'withWastage': withWastage,
                'diaData': diaData
            }
        }
    except Exception as e:
        return {'error': str(e)}
