#!/usr/bin/env python3

import subprocess
import shutil
import os

def main():
    # Ensure we're in the correct directory
    if not os.path.exists("Cargo.toml"):
        print("Error: Cargo.toml not found. Run this script from the mygame directory.")
        return

    print("Building WebAssembly...")
    try:
        subprocess.run(["wasm-pack", "build", "--target", "web"], check=True)
        print("Build successful.")
    except subprocess.CalledProcessError as e:
        print(f"Build failed: {e}")
        return

    target_dir = "../myserver/mygame/pkg"

    if os.path.exists(target_dir):
        shutil.rmtree(target_dir)
    os.makedirs(target_dir)

    # Copy assets
    assets_src = "assets"
    assets_dst = "../myserver/mygame/assets"
    if os.path.exists(assets_src):
        if os.path.exists(assets_dst):
             shutil.rmtree(assets_dst)
        shutil.copytree(assets_src, assets_dst)
        print(f"Assets copied to {assets_dst}")

    print(f"Copying files to {target_dir}...")
    for item in os.listdir("pkg"):
        src = os.path.join("pkg", item)
        dst = os.path.join(target_dir, item)
        if os.path.isdir(src):
            if os.path.exists(dst):
                shutil.rmtree(dst)
            shutil.copytree(src, dst)
        else:
            shutil.copy2(src, dst)

    print("Done! Files copied.")

if __name__ == "__main__":
    main()