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

start_idx = content.find('// H. Cốt thép (Rebar cages)')
end_idx = content.find('groupRebar.add(rebarLines);', start_idx) + len('groupRebar.add(rebarLines);')

if start_idx == -1:
    print("Cannot find start index!")
else:
    rebar_new = """// H. Cốt thép (Rebar cages)
      const rebarSegs = [];
      const longBarDefs = [
        { off: -1.35, y: 0.12 }, { off: 0.0, y: 0.12 }, { off: 1.35, y: 0.12 },
        { off: -1.35, y: 2.88 }, { off: 0.0, y: 2.88 }, { off: 1.35, y: 2.88 }
      ];
      SEGMENT_RANGES.forEach(([a, b]) => {
        const segVertices = [];
        for (let s = a + 0.5; s < b; s += 0.8) {
          const p1 = getPointAt(s, -1.35, 0.12);
          const p2 = getPointAt(s, 1.35, 0.12);
          const p3 = getPointAt(s, 1.35, 2.88);
          const p4 = getPointAt(s, -1.35, 2.88);
          segVertices.push(p1.x, p1.y, p1.z, p2.x, p2.y, p2.z);
          segVertices.push(p2.x, p2.y, p2.z, p3.x, p3.y, p3.z);
          segVertices.push(p3.x, p3.y, p3.z, p4.x, p4.y, p4.z);
          segVertices.push(p4.x, p4.y, p4.z, p1.x, p1.y, p1.z);
        }
        for (const bDef of longBarDefs) {
          for (let i = 0; i < sSamples.length - 1; i++) {
            const sA = sSamples[i];
            const sB = sSamples[i + 1];
            if (sA >= a - 1e-3 && sB <= b + 1e-3) {
              const ptA = getPointAt(sA, bDef.off, bDef.y);
              const ptB = getPointAt(sB, bDef.off, bDef.y);
              segVertices.push(ptA.x, ptA.y, ptA.z, ptB.x, ptB.y, ptB.z);
            }
          }
        }
        const geom = new THREE.BufferGeometry();
        geom.setAttribute('position', new THREE.Float32BufferAttribute(segVertices, 3));
        const mesh = new THREE.LineSegments(geom, new THREE.LineBasicMaterial({ color: 0xf59e0b, linewidth: 1.5 }));
        groupRebar.add(mesh);
        rebarSegs.push(mesh);
      });"""
    content = content[:start_idx] + rebar_new + content[end_idx:]
    with open("app/static/bim/index.html", "w", encoding="utf-8") as f:
        f.write(content)
    print("Rebar updated successfully!")
