with open("app/static/bim/index.html", "r", encoding="utf-8") as f:
    content = f.read()

# 1. Fix groupJoints (Waterstops)
start_idx = content.find('// Băng cản nước V250')
end_idx = content.find('groupJoints.add(new THREE.Mesh(g, new THREE.MeshStandardMaterial({ color: 0xfacc15, side: THREE.DoubleSide })));\n      }') + len('groupJoints.add(new THREE.Mesh(g, new THREE.MeshStandardMaterial({ color: 0xfacc15, side: THREE.DoubleSide })));\n      }')

waterstops_new = """// Băng cản nước V250
      const WATERSTOP_LINES = 4;
      const WATERSTOP_POS = [[-1.375, 0.55], [1.375, 0.55], [-1.375, 2.75], [1.375, 2.75]];
      for (const [u, y] of WATERSTOP_POS.slice(0, WATERSTOP_LINES)) {
        SEGMENT_RANGES.forEach(([a, b], k) => {
          const g = buildLoftGeometry((s) => [getPointAt(s, u, y - 0.125), getPointAt(s, u, y + 0.125)], a, b);
          const m = new THREE.Mesh(g, new THREE.MeshStandardMaterial({ color: 0xfacc15, side: THREE.DoubleSide }));
          m.userData.seg = k;
          groupJoints.add(m);
        });
      }"""
content = content[:start_idx] + waterstops_new + content[end_idx:]

# 2. Fix groupFoundation
start_idx2 = content.find('// D. Móng cống (Đệm cát 10cm + Bê tông lót M100 rộng 3.4m)')
end_idx2 = content.find('groupFoundation.add(foundationMesh);', start_idx2) + len('groupFoundation.add(foundationMesh);')

foundation_new = """// D. Móng cống (Đệm cát 10cm + Bê tông lót M100 rộng 3.4m)
      const foundationSegs = SEGMENT_RANGES.map(([a, b]) => {
        const m = new THREE.Mesh(buildLoftGeometry((s) => [
          getPointAt(s, -1.7, 0.0),
          getPointAt(s, 1.7, 0.0),
          getPointAt(s, 1.7, -0.2),
          getPointAt(s, -1.7, -0.2),
          getPointAt(s, -1.7, 0.0)
        ], a, b), foundationMat);
        groupFoundation.add(m);
        return m;
      });
      const foundationMesh = foundationSegs[0]; // for raycast"""
content = content[:start_idx2] + foundation_new + content[end_idx2:]

with open("app/static/bim/index.html", "w", encoding="utf-8") as f:
    f.write(content)
print("Fixed missing declarations!")
