import requests
import sys
import json
import os

def server():
    # 检查是否传递了足够的参数
    if len(sys.argv) < 5:
        print("Usage: python script.py <pythonfile> <dockerfile> <requirements.txt>")
        sys.exit(1)

    pythonfile = sys.argv[1]
    dockerfile = sys.argv[2]
    requirements_file = sys.argv[3]
    actionname = sys.argv[4]

    # 检查文件是否存在
    if not os.path.exists(pythonfile):
        print(f"Error: {pythonfile} does not exist.")
        sys.exit(1)
    if not os.path.exists(dockerfile):
        print(f"Error: {dockerfile} does not exist.")
        sys.exit(1)
    if not os.path.exists(requirements_file):
        print(f"Error: {requirements_file} does not exist.")
        sys.exit(1)

    url = "http://127.0.0.1:5001/register/function/" + actionname
    
    # 打开文件
    files = [
        ('pythonfile', open(pythonfile, 'rb')),
        ('dockerfile', open(dockerfile, 'rb')),
        ('requirements.txt', open(requirements_file, 'rb'))
    ]

    try:
        # 发送 POST 请求
        reply = requests.post(url=url, files=files, verify=False)
        
        # 检查返回值
        if reply.status_code == 200:
            print("Response:", reply.json())
        else:
            print(f"Failed to register function: {reply.status_code} - {reply.text}")
    except requests.exceptions.RequestException as e:
        print(f"Error occurred: {e}")
    finally:
        # 关闭文件
        for file in files:
            file[1].close()

def main():
    server()

if __name__ == "__main__":
    main()
