from tools import *
from pathlib import Path
from tempfile import TemporaryDirectory
import subprocess
import shutil
import os
import re
import datetime
from tools import convert_zh_to_tw, import_translation_json

# Wasneet聲明
# 這個版本完全是依照「能跑就行」原則寫的,不准糾我錯!

# ==============================
IMPORTLANG = input("语言?(跳过则语言默认为zh_CN)")     # 語言選項
if len(IMPORTLANG) == 0:
    IMPORTLANG = "zh_CN"
VERSION = "v" + input("版本号?(跳过则记录构建日期)") # 版本號
if len(VERSION) == 1:
    VERSION = "构建于" + str(datetime.date.today())
WEBLATE_PATH = os.path.abspath("../weblate")
BUILD_PATH = os.path.abspath("..")                      # MDR留:其他有地方不认字符串啊qwq,以我的能力只会分开写了
SOURCE_DIR = Path("../source").resolve()

# 删除过时构建
os.chdir(BUILD_PATH)                                    #  MDR留:抄的qwq
for file in os.listdir(BUILD_PATH):
    if re.match(r'.+.love', file):
        os.remove(file)
# ==============================

os.chdir(SOURCE_DIR / "translate")
# 拉取weblate仓库更改
print("🟡「提示」 Weblate文本獲取中...")
os.system(f"cd {WEBLATE_PATH} && git pull")
print("🟡「提示」 翻譯文件處理中...")
for lua_file in src_text_path.glob("*.lua"):
    import_translation_json(
        lua_file,
        f"strings/{lua_file.stem}/en_US.json",
        f"strings/{lua_file.stem}/{IMPORTLANG}.json",
        f"text/{IMPORTLANG}/{lua_file.stem}.lua",
    )
os.chdir("..")
PROJECT_ROOT = SOURCE_DIR
LANG_IMAGES = SOURCE_DIR / "images" / IMPORTLANG
BUILD_OUTPUT = f"{BUILD_PATH}/PETRICHOR-{IMPORTLANG} {VERSION}.love"
src_text_path = PROJECT_ROOT / "translate" / "src"

# 7z校驗
if shutil.which("7z") is None:
    print("🔴「錯誤」 沒安裝7-zip找我我能給你變一個出來啊。")
    exit(1)

# 繁瑣的校驗
if not LANG_IMAGES.exists():
    print(f"🔴「錯誤」 哥們我怎麼找不到這個文件夾呢:{LANG_IMAGES}? 應該不是我的鍋吧?")
    exit(1)

print("🟡「提示」 遊戲文件裝箱中...")
original_cwd = os.getcwd()

with TemporaryDirectory() as tmpdir:
    tmp_path = Path(tmpdir)

    shutil.copytree(
        SOURCE_DIR,
        tmp_path,
        ignore=shutil.ignore_patterns(
            'translate/*', 
            'images', 
            '*.py',
            '*.pyc',
            '__pycache__',
            '.git'
        ),
        dirs_exist_ok=True
    )
    # 圖片多言語替換
    shutil.copytree(
        LANG_IMAGES,
        tmp_path / "images",
        dirs_exist_ok=True
    )

    os.chdir(tmp_path)
    command = f'7z a -tzip "{BUILD_OUTPUT}" .' 
    exit_code = os.system(command)
    os.chdir(original_cwd)

    if exit_code != 0:
        print(f"🔴「錯誤」 裝箱失敗,退出碼:{exit_code}。")
        exit(1)

print(f"\n🟢「提示」 裝箱好啦!給你放在{BUILD_OUTPUT}了,記得看一眼嗷。")