Paint in mesh face coordinates on uv texture in python

Say, I have a mesh. The script adds a new lightmap pack uv map, and 1024x1024 texture to it. Then I need to paint. For every point of every face, I need to get x,y,z on the mesh (and normals too) and u,v on the map. Then I need to interpolate 3 or 4 points (depending on the face) to coordinates. If there’s three points then only half of face coordinate is filled. Then, paint on face coordinates, and then, count how many of one pixel in face coordinates. Then math.fsum those instances of one pixel, divide them by the count and write to the texture. After all those faces written, save the texture.