import subprocess
import os
import zipfile
import shutil

def build_ptcgp_zip(zip_name="ptcgp.zip"):
    BASE = os.path.dirname(__file__)   # ptcgpmacro 폴더
    WORK = os.getcwd()                # 사용자가 실행한 위치

    macro3_path = os.path.join(BASE, "macro3.py")
    special_path = os.path.join(BASE, "special.py")
    icon_path = os.path.join(BASE, "vegamax.ico")

    if not os.path.exists(icon_path):
        raise FileNotFoundError(f"Icon not found: {icon_path}")

    # 1. macro3.exe
    subprocess.run([
        "pyinstaller", "--onefile", "--windowed",
        "--name", "VegaMax",
        "--icon", icon_path,
        "--add-data", f"{icon_path};.",
        "--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)

    DIST = os.path.join(WORK, "dist")
    BUILD = os.path.join(WORK, "build")

    # 3. zip
    with zipfile.ZipFile(zip_name, "w", zipfile.ZIP_DEFLATED) as zf:
        zf.write(os.path.join(DIST, "VegaMax.exe"), "VegaMax.exe")
        zf.write(os.path.join(DIST, "PTCGP Account Tool.exe"), "PTCGP Account Tool.exe")

        for f in os.listdir(BASE):
            if f.endswith((".png", ".jpg", ".json")):
                zf.write(os.path.join(BASE, f), f)

    shutil.rmtree(DIST)
    shutil.rmtree(BUILD)

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