##
#  Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
#
#  File :      test_simple_api.py
#
#  Purpose :   Demonstrates how to solve an optimization problem
#              using the single-call submit+solve synchronous API
##

import requests, sys, argparse, json

if __name__ == '__main__':
    # Arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("--url", help="URL of the remote server", type=str, required=True)
    parser.add_argument("--infile", help="Input file to optimize", type=str, required=True)
    parser.add_argument("--intype", help="Content type of the input, for example application/x-mosek-mps", type=str, required=True)
    parser.add_argument("--outtype", help="Content type of the response, for example application/x-mosek-json", type=str, required=True)
    args = parser.parse_args()
    URL = args.url
    infile = args.infile
    intype = args.intype
    outtype = args.outtype
    verify = False # Whether to verify SSL certificates

    # Create a connection
    with requests.Session() as s:
        with open(infile,'rb') as probdata:
            # POST problem data
            submit = s.post(URL + "/api/v1/submit+solve", 
                            data = probdata,
                            headers = { "Content-Type" : intype, "Accept": outtype },
                            verify = verify )
            if submit.status_code == 200:
                if outtype in ["application/json", "application/x-mosek-jtask"]:
                    solution = json.loads(submit.text)
                else:
                    solution = submit.text
                token = submit.headers['X-Mosek-Job-Token']
                res = submit.headers['X-Mosek-Res-Code']
                trm = submit.headers['X-Mosek-Trm-Code']

                ## Obtain the solver log output
                log = s.get(URL + "/api/v1/log", 
                            headers = { "X-Mosek-Job-Token" : token },
                            verify = verify )
                print(log.text)
                print(f"Solution: {solution}")
                print(f"Response code:    {res}")
                print(f"Termination code: {trm}")
            else:
                # In case of error in the first submission
                print(f"Unexpected status {submit.status_code}")
                print(f"Response: {submit.text}")
                print(f"Headers:  {submit.headers}")
