# $ python3 client.py ./thai_curry.jpg ./out.png

import sys
import mimetypes
import base64
import json
import urllib.request

input_file_path = sys.argv[1]
output_file_path = sys.argv[2]

# Optional
options = {"bin": 130, "size": 1000, "base": "w", "png": 1, "auto": 1}


def main():
    if not input_file_path or not output_file_path:
        print("Usage: python3 client.py <input_file_path> <output_file_path>")
        return

    # 画像を読み込んでData URI形式に変換
    data_uri = ""
    mime_type, _ = mimetypes.guess_type(input_file_path)
    with open(input_file_path, "rb") as f:
        data_encoded = base64.b64encode(f.read()).decode()
        data_uri = "data:{};base64,{}".format(mime_type, data_encoded)

    if not data_uri:
        print("Failed to read image file")
        return

    api_url = "https://pointillism.daiiz.dev/api/generate"
    data = json.dumps({"uri": data_uri, **options}).encode()
    req = urllib.request.Request(
        api_url, data=data, headers={"Content-Type": "application/json"}, method="POST"
    )

    with urllib.request.urlopen(req) as res:
        body = res.read()
        with open(output_file_path, "wb") as f:
            f.write(body)


if __name__ == "__main__":
    main()