import re

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

hud_setup = """    // ==========================================
    // HUD Subtitles Setup
    // ==========================================
    const hudCanvas = document.createElement('canvas');
    const hudCtx = hudCanvas.getContext('2d');
    const hudTexture = new THREE.CanvasTexture(hudCanvas);
    hudTexture.minFilter = THREE.LinearFilter;
    const hudMaterial = new THREE.MeshBasicMaterial({ map: hudTexture, transparent: true });
    const hudScene = new THREE.Scene();
    const hudCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 10);
    const hudMesh = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), hudMaterial);
    hudScene.add(hudMesh);

    function renderWithHUD() {
      renderer.autoClear = false;
      renderer.clear();
      renderer.render(scene, camera);
      
      if (isExportingVideo) {
        const w = renderer.domElement.width;
        const h = renderer.domElement.height;
        if (hudCanvas.width !== w || hudCanvas.height !== h) {
          hudCanvas.width = w;
          hudCanvas.height = h;
        }
        hudCtx.clearRect(0, 0, w, h);
        
        const state = computePlanState(currentDay);
        const pad = Math.max(20, w * 0.03);
        const boxH = Math.max(80, h * 0.12);
        const boxY = h - pad - boxH;
        
        hudCtx.fillStyle = 'rgba(15, 23, 42, 0.85)';
        hudCtx.beginPath();
        if (hudCtx.roundRect) {
          hudCtx.roundRect(pad, boxY, w - pad * 2, boxH, 8);
        } else {
          hudCtx.rect(pad, boxY, w - pad * 2, boxH);
        }
        hudCtx.fill();
        
        hudCtx.fillStyle = '#38bdf8';
        const titleSize = Math.floor(boxH * 0.35);
        hudCtx.font = `bold ${titleSize}px sans-serif`;
        hudCtx.fillText(`Ngày ${state.day} / 270 - ${state.date}`, pad + 20, boxY + titleSize + 10);
        
        hudCtx.fillStyle = '#f8fafc';
        const taskSize = Math.floor(boxH * 0.28);
        hudCtx.font = `${taskSize}px sans-serif`;
        const tasks = state.active.map(t => t.name).join(' | ');
        hudCtx.fillText(tasks.length > 120 ? tasks.substring(0, 120) + '...' : tasks, pad + 20, boxY + boxH - 15);
        
        hudTexture.needsUpdate = true;
        renderer.render(hudScene, hudCamera);
      }
    }

    function animate() {"""

content = content.replace("    function animate() {", hud_setup)

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