import re
import sys
import tempfile
import zipfile
from pathlib import Path


def main(path_text):
    path = Path(path_text).resolve()
    with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".xlsx", delete=False) as handle:
        temp = Path(handle.name)
    try:
        with zipfile.ZipFile(path, "r") as source, zipfile.ZipFile(temp, "w", zipfile.ZIP_DEFLATED) as target:
            for item in source.infolist():
                data = source.read(item.filename)
                if item.filename == "xl/styles.xml":
                    text = data.decode("utf-8")
                    text = re.sub(r'<name val="(?:Linux Libertine G|Arial|Calibri|微软雅黑)"\s*/>', '<name val="Microsoft YaHei"/>', text)
                    def normalize_font(match):
                        block = match.group(0)
                        if '<charset ' in block:
                            return re.sub(r'<charset val="[^"]+"\s*/>', '<charset val="134"/>', block)
                        return re.sub(r'(<name val="Microsoft YaHei"\s*/>)', r'\1<charset val="134"/>', block, count=1)
                    text = re.sub(r'<font>.*?</font>', normalize_font, text)
                    data = text.encode("utf-8")
                target.writestr(item, data)
        temp.replace(path)
    finally:
        if temp.exists():
            temp.unlink()
    print(path)


if __name__ == "__main__":
    main(sys.argv[1])
