import esptool
import requests
from pathlib import Path

DOWNLOADS_FOLDER = Path('.downloads')

DEFAULT_BINARY = "https://micropython.org/resources/firmware/ESP32_GENERIC_S3-20240222-v1.22.2.bin"
DEFAULT_PORT = "/dev/ttyACM0"


def save_binary(url: str, file_path: Path):
    response = requests.get(url)
    response.raise_for_status()

    file_path.parent.mkdir(exist_ok=True)
    file_path.write_bytes(response.content)


def flash_binary(file_path: Path, port):
    esptool.main(["--chip", "esp32s3", "--port", port, "erase_flash"])
    print(["-chip", "esp32s3", "--port", port, "write_flash", "-z", "0", file_path])
    esptool.main(["--chip", "esp32s3", "--port", port, "write_flash", "-z", "0", str(file_path)])
    """
    esptool.py --chip esp32s3 --port /dev/ttyACM0 erase_flash
esptool.py --chip esp32s3 --port /dev/ttyACM0 write_flash -z 0 board-20210902-v1.17.bin
"""


if __name__ == '__main__':
    binary_url = None or DEFAULT_BINARY
    downloads_folder = None or DOWNLOADS_FOLDER

    esp_port = None or DEFAULT_PORT

    binary_file_path = Path(downloads_folder, Path(binary_url).name)
    if not binary_file_path.exists():
        save_binary(binary_url, binary_file_path)

    flash_binary(binary_file_path, esp_port)
