# -*- coding: utf-8 -*-
r"""B69: (1) tìm loader nap_du_lieu.py ; (2) tạo build_lam_mau_portal_t41.py từ bản t40 (sửa 5 chỗ)."""
import glob, os, shutil

BH = r'C:\Claw 2\Bao cao - Hanh chinh\BAOCAOTONGHOP'
D = r'C:\Claw 2\Bao cao - Hanh chinh\Bao cao lam mau'

print('  === tìm nap_du_lieu.py (loader CSDL) ===')
import subprocess
r = subprocess.run(['bash', '-lc', 'find "/c/Claw 2" -maxdepth 4 -name "nap_du_lieu.py" 2>/dev/null | head -6'], capture_output=True, text=True)
print('   ', (r.stdout or '').strip() or '(không thấy trong Claw 2)')

print()
print('  === tạo script portal tuần 41 từ bản t40 ===')
src = os.path.join(BH, 'build_lam_mau_portal_t40.py')
dst = os.path.join(BH, 'build_lam_mau_portal_t41.py')
s = open(src, encoding='utf-8', errors='replace').read()
goc = s
thay = [
 (r"SRC = r'C:/Claw 2/Bao cao - Hanh chinh/Bao cao lam mau/da lam sach/Tuan_40_28.09-04.10_DA-LAM-SACH.xlsx'",
  r"SRC = r'C:/Claw 2/Bao cao - Hanh chinh/Bao cao lam mau/da lam sach/Tuan_41_05.10-11.10_DA-LAM-SACH.xlsx'"),
 (r'OUT = r"C:/Claw 2/Bao cao - Hanh chinh/BAOCAOTONGHOP/HTML/Tuan 40/Bao_cao_LamMau_Tuan40_Portal.html"',
  r'OUT = r"C:/Claw 2/Bao cao - Hanh chinh/BAOCAOTONGHOP/HTML/Tuan 41/Bao_cao_LamMau_Tuan41_Portal.html"'),
 ("TUAN = '40'", "TUAN = '41'"),
 ("KY_TEXT = '28/09 → 04/10/2026'", "KY_TEXT = '05/10 → 11/10/2026'"),
 ("<title>Báo cáo Làm mẫu — Tuần 40 (28/09 → 04/10/2026)</title>",
  "<title>Báo cáo Làm mẫu — Tuần 41 (05/10 → 11/10/2026)</title>"),
]
for a, b in thay:
    if a not in s:
        print('   ⚠ KHÔNG THẤY để thay: %s' % a[:80])
    s = s.replace(a, b)
print('   số chỗ đã đổi: %d ký tự khác đi' % (len(s) - len(goc)))
open(dst, 'w', encoding='utf-8', newline='').write(s)
print('   đã tạo: %s (%d B)' % (os.path.basename(dst), os.path.getsize(dst)))
print()
print('   === 6 dòng cấu hình trong bản mới ===')
for i, l in enumerate(s.split('\n')[:60], 1):
    if any(k in l for k in ('SRC =', 'OUT =', 'TUAN =', 'KY_TEXT =', '<title>')):
        print('   %-4d %s' % (i, l.strip()[:140]))
tail = [l for l in s.split('\n') if 'Tuan 4' in l or 'Tuần 4' in l]
print()
print('   còn sót chuỗi tuần 40 trong file mới: %d dòng' % len(tail))
for l in tail[:6]:
    print('     - %s' % l.strip()[:140])
