import re

with open("app/static/bim/index.html", "r", encoding="utf-8") as f:
    content = f.read()

new_gantt_phases = """    const GANTT_PHASES = [
      { id: 'I', name: 'GĐ I: Chuẩn bị, mặt bằng & lán trại', start: '2026-09-25', end: '2026-10-10' },
      { id: 'II', name: 'GĐ II: Thi công Phân đoạn 1 (50 m từ nhà ông Đèn)', start: '2026-10-11', end: '2026-12-20' },
      { id: 'III', name: 'GĐ III: Thi công Phân đoạn 2 (50 m)', start: '2026-12-21', end: '2027-03-15' },
      { id: 'IV', name: 'GĐ IV: Thi công Phân đoạn 3 (45 m + cửa cống) & hố ga', start: '2027-03-16', end: '2027-06-15' },
      { id: 'V', name: 'GĐ V: Bàn giao', start: '2027-06-16', end: '2027-06-21' }
    ];"""

new_gantt_tasks = """    // 27 hạng mục Gantt cuốn chiếu
    const GANTT_TASKS = [
      ['1', 'Lán trại, kho bãi, thuê bãi 1.500 m²', '2026-09-25', '2026-10-10'],
      // Phase I
      ['2', 'Đắp đê quai, múc bùn & đào đất PĐ1', '2026-10-11', '2026-10-25'],
      ['3', 'Đóng cọc tre 25 cọc/m² PĐ1', '2026-10-26', '2026-11-05'],
      ['4', 'Ép cừ U250 PĐ1', '2026-11-06', '2026-11-15'],
      ['5', 'Lắp dầm văng chống ngang PĐ1', '2026-11-16', '2026-11-20'],
      ['6', 'BT lót, cốt thép, BT đáy PĐ1', '2026-11-21', '2026-11-25'],
      ['7', 'Cốt thép, ván khuôn, BT tường PĐ1', '2026-11-26', '2026-12-05'],
      ['8', 'Cốt thép, ván khuôn, BT nắp PĐ1', '2026-12-06', '2026-12-15'],
      ['9', 'Tháo văng, rút cừ, đắp hoàn trả PĐ1', '2026-12-16', '2026-12-20'],
      // Phase II
      ['10', 'Đắp đê quai, múc bùn & đào đất PĐ2', '2026-12-21', '2027-01-05'],
      ['11', 'Đóng cọc tre 25 cọc/m² PĐ2', '2027-01-06', '2027-01-15'],
      ['12', 'Ép cừ U250 PĐ2', '2027-01-16', '2027-01-25'],
      ['13', 'Lắp dầm văng chống ngang PĐ2', '2027-01-26', '2027-01-31'],
      ['14', 'BT lót, cốt thép, BT đáy PĐ2', '2027-02-01', '2027-02-05'],
      ['15', 'Cốt thép, ván khuôn, BT tường PĐ2', '2027-02-06', '2027-02-20'],
      ['16', 'Cốt thép, ván khuôn, BT nắp PĐ2', '2027-02-21', '2027-02-28'],
      ['17', 'Tháo văng, rút cừ, đắp hoàn trả PĐ2', '2027-03-01', '2027-03-15'],
      // Phase III
      ['18', 'Đắp đê quai, múc bùn & đào đất PĐ3', '2027-03-16', '2027-03-31'],
      ['19', 'Đóng cọc tre 25 cọc/m² PĐ3', '2027-04-01', '2027-04-10'],
      ['20', 'Ép cừ U250 PĐ3', '2027-04-11', '2027-04-20'],
      ['21', 'Lắp dầm văng chống ngang PĐ3', '2027-04-21', '2027-04-25'],
      ['22', 'BT lót, cốt thép, BT đáy PĐ3', '2027-04-26', '2027-04-30'],
      ['23', 'Cốt thép, ván khuôn, BT tường PĐ3', '2027-05-01', '2027-05-15'],
      ['24', 'Cốt thép, ván khuôn, BT nắp PĐ3', '2027-05-16', '2027-05-30'],
      ['25', 'Xây hố ga, cửa xả', '2027-05-20', '2027-05-30'],
      ['26', 'Tháo văng, rút cừ, đắp hoàn trả PĐ3', '2027-06-01', '2027-06-15'],
      ['27', 'Hoàn thiện, dọn dẹp, bàn giao toàn tuyến', '2027-06-16', '2027-06-21']
    ].map(([id, name, s, e]) => ({ id, name, start: s, end: e, d0: dayOf(s), d1: dayOf(e) }));"""

new_seg_plan = """    // Kế hoạch hình học theo phân đoạn (ánh xạ hạng mục Gantt cuốn chiếu → cấu kiện)
    const SEG_PLAN = [
      { dyke_excav: ['2026-10-11', '2026-10-25'], bamboo: ['2026-10-26', '2026-11-05'], pile: ['2026-11-06', '2026-11-15'], strut: ['2026-11-16', '2026-11-20'], lean: ['2026-11-21', '2026-11-25'], wall: ['2026-11-26', '2026-12-05'], slab: ['2026-12-06', '2026-12-15'], pull: ['2026-12-16', '2026-12-20'] },
      { dyke_excav: ['2026-12-21', '2027-01-05'], bamboo: ['2027-01-06', '2027-01-15'], pile: ['2027-01-16', '2027-01-25'], strut: ['2027-01-26', '2027-01-31'], lean: ['2027-02-01', '2027-02-05'], wall: ['2027-02-06', '2027-02-20'], slab: ['2027-02-21', '2027-02-28'], pull: ['2027-03-01', '2027-03-15'] },
      { dyke_excav: ['2027-03-16', '2027-03-31'], bamboo: ['2027-04-01', '2027-04-10'], pile: ['2027-04-11', '2027-04-20'], strut: ['2027-04-21', '2027-04-25'], lean: ['2027-04-26', '2027-04-30'], wall: ['2027-05-01', '2027-05-15'], slab: ['2027-05-16', '2027-05-30'], pull: ['2027-06-01', '2027-06-15'] }
    ].map(p => Object.fromEntries(Object.entries(p).map(([k, [s, e]]) => [k, [dayOf(s), dayOf(e)]])));
    const PLAN_MANHOLE = [dayOf('2027-05-20'), dayOf('2027-05-30')];
    // PLAN_PULL removed because pulling is now per segment!"""

new_compute_plan_state = """    function computePlanState(day) {
      const cum = { larsen: 0, bamboo: 0, concrete: 0, rebar: 0, earth: 0 };
      SEG_PLAN.forEach((p, k) => {
        cum.larsen += QTY_SEG.larsen[k] * progressOf(day, p.pile);
        cum.earth += QTY_SEG.earth[k] * progressOf(day, p.dyke_excav);
        cum.bamboo += QTY_SEG.bamboo[k] * progressOf(day, p.bamboo);
        // BT/thép: đáy (theo hạng mục lót+đáy), tường, nắp — tỷ trọng theo TĐ
        const c = QTY_SEG.concrete[k], r = QTY_SEG.rebar[k];
        const wB = k < 2 ? 42 / 146.5 : 49.867 / 146.636, wW = k < 2 ? 67 / 146.5 : 63.019 / 146.636;
        cum.concrete += c * (wB * progressOf(day, p.lean) + wW * progressOf(day, p.wall) + (1 - wB - wW) * progressOf(day, p.slab));
        const rB = k < 2 ? 5.306 / 19.756 : 4.783 / 18.124, rW = k < 2 ? 9.145 / 19.756 : 8.558 / 18.124;
        cum.rebar += r * (rB * progressOf(day, p.lean) + rW * progressOf(day, p.wall) + (1 - rB - rW) * progressOf(day, p.slab));
      });
      const phase = GANTT_PHASES.find(ph => day >= dayOf(ph.start) && day <= dayOf(ph.end)) || GANTT_PHASES[GANTT_PHASES.length - 1];
      const active = GANTT_TASKS.filter(t => day >= t.d0 && day <= t.d1);
      return { day, date: dateOfDay(day), phase, active, cum };
    }"""

new_update_bim_state = """    // ==========================================
    // 9. 4D BIM — HIỂN THỊ CẤU KIỆN THEO KẾ HOẠCH
    // ==========================================
    // Giả định kỹ thuật (Gantt không ghi): tháo văng của một phân đoạn khi đổ xong tường phân đoạn đó.
    function updateBim4DState(day) {
      SEG_PLAN.forEach((p, k) => {
        const started = day >= p.pile[0];
        const pPile = progressOf(day, p.pile);
        const pPull = progressOf(day, p.pull);
        for (const m of larsenSegMeshes[k]) {
          m.visible = started && pPull < 1;
          // Ép: cừ hạ dần từ trên xuống; rút: nâng dần lên
          m.position.y = pPull > 0 ? SHEET_PILE_LENGTH * pPull : SHEET_PILE_LENGTH * (1 - pPile);
        }
        groupDyke.children.forEach((d, i) => {
          if (i === k || (k === 2 && i === 3)) d.visible = day >= p.dyke_excav[0] && pPull < 1;
        });
        culvertSegs[k].visible = day >= p.wall[1];
        topSlabSegs[k].visible = day >= p.slab[1];
      });
      groupStruts.children.forEach(m => {
        const p = SEG_PLAN[m.userData.seg ?? 0];
        m.visible = day >= p.strut[0] && day < p.pull[0];
      });
      groupLarsen.visible = true;
      groupStruts.visible = true;

      // Cọc tre: hiện dần theo mặt trước thi công từng phân đoạn
      let front = 0;
      SEG_PLAN.forEach((p, k) => {
        const [a, b] = SEGMENT_RANGES[k];
        const pr = progressOf(day, p.bamboo);
        if (pr > 0) front = a + pr * (b - a);
      });
      groupBamboo.visible = front > 0;
      bambooInstanced.count = Math.min(totalPilesCount, Math.floor(front / PILE_GRID) * pileOffsets.length);
      bambooInstanced.instanceMatrix.needsUpdate = true;

      groupFoundation.visible = day >= SEG_PLAN[0].lean[0];
      groupRebar.visible = day >= SEG_PLAN[0].lean[0];
      groupJoints.visible = day >= SEG_PLAN[0].wall[0];

      // Hố ga (#25): xuất hiện lần lượt 5 ga trong khoảng 20/05–30/05/2027
      const nGa = Math.round(progressOf(day, PLAN_MANHOLE) * chamberStations.length);
      groupManhole.visible = nGa > 0;
      groupManhole.children.forEach((m, i) => { m.visible = Math.floor(i / 2) < nGa; });
      groupWing.visible = day >= SEG_PLAN[2].wall[1];
    }"""


# Replace phases
content = re.sub(r'const GANTT_PHASES = \[\s+.*?\];', new_gantt_phases, content, flags=re.DOTALL)

# Replace tasks
content = re.sub(r'// \d+ hạng mục Gantt.*?\].map\(\(\[id, name, s, e\]\) => \(.*?\}\)\);', new_gantt_tasks, content, flags=re.DOTALL)

# Replace SEG_PLAN and PLAN_MANHOLE/PLAN_PULL
content = re.sub(r'const SEG_PLAN = \[\s+.*?\]\.map\(p => .*?\)\)\)\);.*?const progressOf', new_seg_plan + '\n    const progressOf', content, flags=re.DOTALL)

# Replace computePlanState
content = re.sub(r'function computePlanState\(day\) \{.*?return \{ day, date: dateOfDay\(day\), phase, active, cum \};\n    \}', new_compute_plan_state, content, flags=re.DOTALL)

# Replace updateBim4DState
content = re.sub(r'// ==========================================\s+// 9\. 4D BIM — HIỂN THỊ CẤU KIỆN THEO KẾ HOẠCH\s+// ==========================================.*?function updateBim4DState\(day\) \{.*?\n    \}', new_update_bim_state, content, flags=re.DOTALL)

with open("app/static/bim/index.html", "w", encoding="utf-8") as f:
    f.write(content)
print("Updated successfully")
