import subprocess
import os
import zipfile
import shutil

def build_ptcgp_zip(zip_name="ptcgp.zip"):
    """macro3.py, special.py 빌드 후 ptcgp.zip 생성"""
    cwd = os.path.dirname(__file__)
    
    macro3_path = os.path.join(cwd, "macro3.py")
    special_path = os.path.join(cwd, "special.py")
    
    # 1️⃣ macro3.exe 빌드
    subprocess.run([
        "pyinstaller", "--onefile", "--windowed",
        "--name", "VegaMax",
        "--icon=vegamax.ico",
        "--add-data", "vegamax.ico;.",
        "--hidden-import=cv2", "--collect-submodules=cv2",
        "--hidden-import=numpy",
        "--hidden-import=PyQt6", "--hidden-import=PyQt6.QtWidgets",
        "--hidden-import=PyQt6.QtGui", "--hidden-import=PyQt6.QtCore",
        macro3_path
    ], check=True)

    # 2️⃣ special.exe 빌드
    subprocess.run([
        "pyinstaller", "-F", "-w",
        "--name", "PTCGP Account Tool",
        "--hidden-import=PyQt6",
        "--hidden-import=PyQt6.QtWidgets",
        "--hidden-import=PyQt6.QtGui",
        "--hidden-import=PyQt6.QtCore",
        special_path
    ], check=True)

    # 3️⃣ zip 생성
    with zipfile.ZipFile(zip_name, "w", zipfile.ZIP_DEFLATED) as zf:
        # exe 추가 (dist 폴더에서)
        zf.write(os.path.join(cwd, "dist", "VegaMax.exe"), "VegaMax.exe")
        zf.write(os.path.join(cwd, "dist", "PTCGP Account Tool.exe"), "PTCGP Account Tool.exe")
        
        # 이미지 + JSON 추가
        for f in os.listdir(cwd):
            if f.endswith(".png") or f.endswith(".jpg") or f.endswith(".json"):
                zf.write(os.path.join(cwd, f), f)

    # 4️⃣ 임시 빌드 폴더 정리
    shutil.rmtree(os.path.join(cwd, "dist"))
    shutil.rmtree(os.path.join(cwd, "build"))
    for spec_file in ["VegaMax.spec", "PTCGP Account Tool.spec"]:
        spec_path = os.path.join(cwd, spec_file)
        if os.path.exists(spec_path):
            os.remove(spec_path)

    print(f"{zip_name} 생성 완료")
