# -*- coding: utf-8 -*-
r"""B113: tạo clean_sx_t41_only.py từ bản T40 (chỉ đổi glob + tên sheet đích), grep dấu vết tuần cũ, rồi CHẠY."""
import os, re, subprocess, sys

LAM = r'C:\Claw 2\Bao cao - Hanh chinh\Bao-cao-sx\LAMSACH'
src = os.path.join(LAM, 'clean_sx_t40_only.py')
dst = os.path.join(LAM, 'clean_sx_t41_only.py')
s = open(src, encoding='utf-8').read()
s2 = s.replace("BẢNG BC TÌNH HÌNH SX - TUẦN 40.xlsx", "BẢNG BC TÌNH HÌNH SX - TUẦN 41.xlsx")
s2 = s2.replace("ws_out.title = 'T40'", "ws_out.title = 'T41'")
open(dst, 'w', encoding='utf-8').write(s2)
print('  đã tạo:', dst, os.path.getsize(dst), 'B')
print('  các dòng còn dấu vết tuần 40/39:')
con = [ (i + 1, l.strip()) for i, l in enumerate(s2.splitlines()) if re.search(r'T40|T39|TUẦN 40|TUẦN 39', l) ]
for i, l in con:
    print('    %d| %s' % (i, l[:120]))
print('  → tổng %d dòng cần xem (chỉ chấp nhận nếu là so sánh tuần trước hoặc văn bản mô tả)' % len(con))
if not con:
    print('  ✓ sạch dấu vết tuần cũ')

print()
print('  === CHẠY clean_sx_t41_only.py ===')
r = subprocess.run([sys.executable, dst], capture_output=True, text=True, encoding='utf-8', errors='replace',
                   cwd=LAM, timeout=600)
out = (r.stdout or '') + (r.stderr or '')
print(out[-1500:])
print('  exit =', r.returncode)
ket = os.path.join(LAM, 'KETQUA', 'BANG_BC_SX_TUAN_41_DA-LAM-SACH.xlsx')
print('  file sạch:', ket, os.path.exists(ket) and ('%d B' % os.path.getsize(ket)) or 'CHƯA CÓ')
