Cavity assisted measurements of heat and work in optical lattices