# -*- coding: utf-8 -*-
"""Sửa SERVER calib theo yêu cầu chủ nhân:
  - nhãn form: '% màu pha trong base' + nêu điều kiện chuẩn
  - trang chi tiết: hiện điều kiện; khi có đề xuất hiệu chỉnh thì HIỆN BẢNG + ô MẬT KHẨU để xác nhận
  - POST /ap-dung: kiểm mật khẩu (mặc định 19842026 trong pass_hieu_chinh.txt) rồi mới ghi vào CSDL B
"""
import ast

P = r'C:\Claw 2\Nghien cuu\Du-an-B-He-mau-Stain-Glaze\calib-app\server_calib.py'
s = open(P, encoding='utf-8').read()


def thay(cu, moi, bat_buoc=True):
    global s
    if cu not in s:
        if bat_buoc:
            raise SystemExit('KHÔNG TÌM THẤY đoạn cần sửa:\n' + cu[:160])
        return
    s = s.replace(cu, moi)


# 1. hằng số + hàm đọc mật khẩu hiệu chỉnh
thay("""MK_FILE = os.path.join(GOC, 'mat_khau.txt')""",
     """MK_FILE = os.path.join(GOC, 'mat_khau.txt')
PASS_FILE = os.path.join(GOC, 'pass_hieu_chinh.txt')
DIEU_KIEN = ('Kéo màu bằng CÙNG thước kéo với màu mẫu · pha trong CÙNG loại base với mẫu · '
             'trên GIẤY TRẮNG cùng loại · tỉ lệ nhập là % màu pha trong base')""")

thay("""def bi_mat():""",
     """def pass_hieu_chinh():
    try:
        return open(PASS_FILE, encoding='utf-8').read().strip() or '19842026'
    except Exception:
        return '19842026'


def bi_mat():""")

# 2. nhãn form: % màu trong base
thay('''<label>Ghi chú (tỉ lệ tính theo khối lượng bột màu / dung dịch màu)</label><input type="text" name="ghi_chu" placeholder="VD: hỗn hợp thử trên nền giấy trắng, pha 10%% dung dịch"></div></div>''',
     '''<label>Ghi chú (tùy chọn)</label><input type="text" name="ghi_chu" placeholder="VD: kéo bằng thước 100 µm, base BA123, giấy trắng"></div></div>''')
thay('''<label>Thành phần hỗn hợp</label>''',
     '''<label>Thành phần — nhập <b>% màu pha trong base</b> của từng màu (không cần cộng = 100%%)</label>
<div style="background:#eafaf0;border:1px solid #bfe3cd;border-radius:8px;padding:8px 10px;margin:4px 0 8px"><small><b>Điều kiện chuẩn (mặc định):</b> kéo màu bằng <b>cùng thước kéo</b> với màu mẫu · pha trong <b>cùng loại base</b> với mẫu · trên <b>giấy trắng cùng loại</b>.</small></div>''')
thay(''' placeholder="%%" value="''', ''' placeholder="% trong base" value="''')
thay('''<p id="tb"><small>Tổng tỉ lệ nên = 100%%.</small></p>''',
     '''<p id="tb"><small>Ví dụ: Black 27 điền <b>4</b> nghĩa là 4%% màu đó trong base. Tổng chỉ để tham chiếu, không cần = 100%%.</small></p>''')

# 3. lưu điều kiện chuẩn khi tạo hỗn hợp
thay("""            cur = con Pitts""".replace(' Pitts', ''), """            cur = con Pitts""".replace(' Pitts', ''))  # no-op giữ chỗ
thay("""            cur = con.execute('''INSERT INTO hon_hop (tao_luc,nguoi_nhap,ghi_chu,thanh_phan,tong_ti_le,trang_thai)
                                 VALUES (?,?,?,?,?, 'cho_du_doan')''',""",
     """            cur = con.execute('''INSERT INTO hon_hop (tao_luc,nguoi_nhap,ghi_chu,thanh_phan,tong_ti_le,trang_thai,dieu_kien)
                                 VALUES (?,?,?,?,?, 'cho_du_doan', ?)''',""")
thay("""                               json.dumps(tp, ensure_ascii=False), float(fs.getvalue('tong_ti_le', 0) or 0)))""",
     """                               json.dumps(tp, ensure_ascii=False), float(fs.getvalue('tong_ti_le', 0) or 0), DIEU_KIEN))""")

# 4. trang chi tiết: hiện điều kiện + bảng đề xuất + ô mật khẩu xác nhận
thay('''tai = ''
    if v['du_doan_hex'] and v['trang_thai'] != 'da_doi_chieu':''',
     '''tai = ''
    chua_dc = v['trang_thai'] in ('cho_du_doan', 'da_du_doan', 'cho') or not v['du_doan_hex']
    if v['du_doan_hex'] and chua_dc and not v['thuc_te_hex']:''')
thay("""    if v['thuc_te_hex']:
        dE = v['delta_E'] or 0""",
     """    if v['thuc_te_hex']:
        dE = v['delta_E'] or 0
        con0 = db()
        cho_ap = con0.execute('SELECT id,mau_ten,gia_tri_cu,gia_tri_moi,lab_moi,ly_do FROM hieu_chinh_mau '
                              'WHERE hon_hop_id=? AND da_ap_dung=0 ORDER BY id', (v['id'],)).fetchall()
        con0.close()""")
thay("""        elif v['trang_thai'] == 'da_doi_chieu':
            tai += '<p><small>AGY kết luận chưa cần hiệu chỉnh (ΔE nhỏ).</small></p>'""",
     """        elif v['trang_thai'] in ('cho_xac_nhan', 'da_doi_chieu'):
            tai += '<p><small>AGY kết luận chưa cần hiệu chỉnh (ΔE nhỏ) — không có đề xuất nào.</small></p>'""")
thay("""        hc = con.execute('SELECT mau_ten,gia_tri_cu,gia_tri_moi,ly_do FROM hieu_chinh_mau WHERE hon_hop_id=?', (v['id'],)).fetchall()
        con.close()
        if hc:""",
     """        hc = con.execute('SELECT mau_ten,gia_tri_cu,gia_tri_moi,ly_do FROM hieu_chinh_mau WHERE hon_hop_id=? AND da_ap_dung=1', (v['id'],)).fetchall()
        con.close()
        if hc:""")
thay("""    elif v['trang_thai'] == 'da_du_doan':
        tai += '<p><small>Đã nhận ảnh — agent sẽ tự đối chiếu (trang tự cập nhật mỗi 10 giây).</small></p>'
    tai += '</div>'""",
     """    elif v['trang_thai'] == 'da_du_doan':
        tai += '<p><small>Đã nhận ảnh — agent sẽ tự đối chiếu (trang tự cập nhật mỗi 10 giây).</small></p>'
    if v['thuc_te_hex'] and cho_ap:
        dong = ''.join('<tr><td>%s</td><td>%s</td><td><b>%s</b></td><td><small>%s</small></td></tr>'
                       % (html.escape(r[1] or ''), html.escape(str(r[2])), html.escape(str(r[3])), html.escape((r[5] or '')[:160]))
                       for r in cho_ap)
        tai += ('<h3 style="color:#8a1414">ĐỀ XUẤT HIỆU CHỈNH — chưa ghi vào CSDL B</h3>'
                '<table><tr><th>Màu</th><th>Hệ số cũ</th><th>Hệ số mới</th><th>Lý do</th></tr>%s</table>'
                '<form method="post" action="ap-dung?id=%s" style="margin-top:8px">'
                '<label>Nhập mật khẩu xác nhận để GHI vào CSDL B</label>'
                '<input type="password" name="mat_khau" required placeholder="mật khẩu hiệu chỉnh" style="max-width:240px">'
                '<button type="submit">Xác nhận &amp; ghi vào CSDL B</button></form>'
                '<p><small>Chưa nhập mật khẩu thì CSDL B giữ nguyên — AGY chỉ đề xuất.</small></p>' % (dong, v['id']))
    tai += '</div>'""")

# 5. CSS thêm trạng thái mới
thay(""".cho_du_doan{background:#fff3cd;color:#7a5b00}.da_du_doan{background:#cfe4ff;color:#0a3d75}.da_doi_chieu{background:#d6f4e0;color:#0b5c2e}""",
     """.cho_du_doan{background:#fff3cd;color:#7a5b00}.da_du_doan{background:#cfe4ff;color:#0a3d75}
.da_doi_chieu,.cho_xac_nhan{background:#ffe4cc;color:#8a4a00}.da_hieu_chinh{background:#d6f4e0;color:#0b5c2e}""")

# 6. POST /ap-dung
thay("""        if duong == '/tai-anh':""",
     """        if duong == '/ap-dung':
            dai = int(self.headers.get('Content-Length') or 0)
            fs = cgi.FieldStorage(fp=io.BytesIO(self.rfile.read(dai)), headers=self.headers,
                                  environ={'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers.get('Content-Type', '')})
            hid = int(urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query).get('id', ['0'])[0])
            if fs.getvalue('mat_khau', '').strip() != pass_hieu_chinh():
                print('[%s] hỗn hợp #%d: SAI mật khẩu xác nhận hiệu chỉnh' % (time.strftime('%H:%M:%S'), hid))
                self.send_response(302)
                self.send_header('Location', './hon-hop?id=%d&sai_pass=1' % hid)
                self.end_headers()
                return
            import importlib.util
            spec = importlib.util.spec_from_file_location('wcal', os.path.join(GOC, 'worker_calib.py'))
            m = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(m)
            con = db()
            n, mo = m.ap_dung(con, hid)
            con.close()
            print('[%s] hỗn hợp #%d: ĐÃ GHI hiệu chỉnh %d màu vào CSDL B' % (time.strftime('%H:%M:%S'), hid, n))
            self.send_response(302)
            self.send_header('Location', './hon-hop?id=%d&da_ap=%d' % (hid, n))
            self.end_headers()
            return
        if duong == '/tai-anh':""")

# 7. băng báo khi áp dụng xong / sai mật khẩu
thay("""    if q.get('da_tai'):""",
     """    if q.get('sai_pass'):
        kq = ('<div class="the" style="border-color:#8a1414;background:#ffecec"><b style="color:#8a1414">✖ Sai mật khẩu xác nhận.</b> '
              'CSDL B KHÔNG bị thay đổi. Nhập lại mật khẩu hiệu chỉnh ở mục ĐỀ XUẤT bên dưới.</div>') + kq
    if q.get('da_ap'):
        kq = ('<div class="the" style="border-color:#0b6b3a;background:#eafaf0"><b>✔ Đã ghi %s màu vào CSDL B.</b> '
              'Xem chi tiết ở mục <a href="hieu-chinh">Lịch sử hiệu chỉnh</a>.</div>' % q['da_ap'][0]) + kq
    if q.get('da_tai'):""")

open(P, 'w', encoding='utf-8').write(s)
ast.parse(s)
print('server_calib.py: đã sửa + cú pháp OK')
for k in ('pass_hieu_chinh', '/ap-dung', '% màu pha trong base', 'ĐỀ XUẤT HIỆU CHỈNH', 'cho_xac_nhan'):
    print('   có %-22s: %s' % (k, k in s))
