# -*- coding: utf-8 -*-
"""Sửa lỗi liên kết tương đối của app CALIB: thêm <base> để mọi liên kết luôn trỏ đúng gốc (/ hoặc /calib/).
Nguyên nhân lỗi: từ trang /calib/lich-su/ mà bấm liên kết tương đối 'hon-hop?id=2' thì trình duyệt nối thành
/calib/lich-su/hon-hop?id=2 → 404 → không thấy ô tải ảnh.
"""
import ast, re, sys

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()

BASE_JS = ("<script>var B=(location.pathname.indexOf('/calib')===0)?'/calib/':'/';"
           "document.write('<base href=\"'+B+'\">');</script>")

# 1. Bỏ đoạn tự thêm '/' cuối đường dẫn (nguồn gốc lỗi) ở mọi trang
s = s.replace("<script>if(!location.pathname.endsWith('/'))location.replace(location.pathname+'/'+location.search);</script>", '')

# 2. Thêm <base> ngay đầu mỗi trang (đặt trước <style> để mọi liên kết/ảnh giải đúng gốc)
s = s.replace("<style>%s</style><header><b>CALIB CSDL B</b><span>Huấn luyện &amp; hiệu chỉnh màu</span></header>",
              BASE_JS + "<style>%s</style><header><b>CALIB CSDL B</b><span>Huấn luyện &amp; hiệu chỉnh màu</span></header>")
s = s.replace("<style>%s</style>\n<header><b>CALIB CSDL B</b><span>Hỗn hợp màu", BASE_JS + "<style>%s</style>\n<header><b>CALIB CSDL B</b><span>Hỗn hợp màu")
s = s.replace("<style>%s</style><header><b>HỖN HỢP #%s</b>", BASE_JS + "<style>%s</style><header><b>HỖN HỢP #%s</b>")
s = s.replace("'<style>%s</style><header><b>LỊCH SỬ HỖN HỢP</b></header>", "'" + BASE_JS + "<style>%s</style><header><b>LỊCH SỬ HỖN HỢP</b></header>")
s = s.replace("'<style>%s</style><header><b>HIỆU CHỈNH CSDL B</b></header>", "'" + BASE_JS + "<style>%s</style><header><b>HIỆU CHỈNH CSDL B</b></header>")

# 3. JS fetch dùng đúng tiền tố (B đã tính ở trên) thay vì B=''
s = s.replace("const B='';", "const B=(location.pathname.indexOf('/calib')===0)?'/calib/':'/';")

open(P, 'w', encoding='utf-8').write(s)
ast.parse(s)
print('đã sửa server_calib.py: cú pháp OK')
print('   số lần xuất hiện <base>:', s.count("document.write('<base href="))
print('   còn script tự thêm / cuối:', s.count("endsWith('/'))location.replace"))
