# -*- coding: utf-8 -*-
"""B25: THỬ bộ vá đường dẫn trên BẢN COPY (không đụng bản gốc), rồi kiểm cú pháp shell/python."""
import os, re, shutil, subprocess, sys

NGUON = r'C:\Claw 2\_BAN_GIAO_APP_LINUX\BAN_GIAO_APP_LINUX'
T = os.path.join(os.environ['LOCALAPPDATA'], 'Temp', 'bg_test')
if os.path.exists(T):
    shutil.rmtree(T)
os.makedirs(T, exist_ok=True)
dst = os.path.join(T, 'BAN_GIAO_APP_LINUX')
shutil.copytree(NGUON, dst)
print('  đã copy bản thử ->', dst)

PY = sys.executable
r = subprocess.run([PY, os.path.join(dst, 'cai_dat', 'sua_duong_dan.py')], capture_output=True, text=True, encoding='utf-8', errors='replace')
print('  --- kết quả vá ---')
print(r.stdout.strip()[-2500:])
if r.stderr.strip():
    print('  STDERR:', r.stderr.strip()[-500:])

print()
print('  === kiểm dòng then chốt sau khi vá ===')
for f in ['apps/hlqt/server_hlqt.py', 'apps/hlqt/worker_hlqt.py', 'apps/calib/server_calib.py',
          'apps/calib/worker_calib.py', 'apps/lab/server_lab.py', 'apps/lab/worker_lab.py',
          'apps/hlqt/goi_kien_thuc_hlqt.py']:
    p = os.path.join(dst, f)
    print('  ---', f)
    for i, dong in enumerate(open(p, encoding='utf-8', errors='replace'), start=1):
        if re.search(r"^(GOC|APP|DB|D_DB|AGY|MODEL|PROJECT|URL_PUBLIC|MAIL_SCRIPT|MD2DOCX|CONG|OUT|VIEC|KIEN_THUC)", dong.strip()):
            print('     %3d| %s' % (i, dong.rstrip()[:120]))

print()
print('  === bash -n (kiểm cú pháp shell) ===')
for f in ['cai_dat/cai_dat.sh', 'cai_dat/chay_app.sh', 'cai_dat/chay_tat_ca.sh', 'cai_dat/dung_tat_ca.sh', 'cai_dat/kiem_tra.sh']:
    p = os.path.join(dst, f)
    q = subprocess.run(['bash', '-n', p.replace('\\', '/')], capture_output=True, text=True)
    print('   %-26s %s' % (f, 'OK' if q.returncode == 0 else 'LỖI: ' + (q.stderr or '').strip()[:120]))

print()
print('  === mô phỏng chạy cai_dat.sh với root = bản thử (chỉ tạo venv thì bỏ, kiểm phần logic) ===')
import json
cfg = json.load(open(os.path.join(dst, 'cai_dat', 'cau_hinh.json'), encoding='utf-8'))
print('   cau_hinh.json:', json.dumps(cfg, ensure_ascii=False)[:200])
