#!/usr/bin/env python
import argparse
import json
from termcolor import colored

"""
Script to generate a valid OpenAPI descriptor version 3 accepted by different tools.
The script fix missing elements causing the errors.
"""

DEFAULT_ENCODING = "utf-8"


def print_error(msg):
    print(colored(f"[!] {msg}", "red"))


def fix(file_descriptor_path):
    openapi_descriptor_fixed = None
    # Load the source descriptor
    with open(file_descriptor_path, "r", encoding=DEFAULT_ENCODING) as f:
        openapi_descriptor = json.load(f)
    # Ensure that is a v3
    if "openapi" not in openapi_descriptor:
        print_error("No 'openapi' attribute found!")
        return openapi_descriptor_fixed
    version = openapi_descriptor["openapi"]
    if version.startswith("2."):
        print_error(f"Version {version} not supported!")
        return openapi_descriptor_fixed
    # Apply fixes when needed
    if "servers" not in openapi_descriptor:
        openapi_descriptor["servers"] = []
    if len(openapi_descriptor["servers"]) == 0:
        openapi_descriptor["servers"].append({"url": "https://host.com"})
    # Generate the json string of the fixed descriptor
    openapi_descriptor_fixed = json.dumps(openapi_descriptor, indent=2)
    return openapi_descriptor_fixed


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Script to generate a valid OpenAPI descriptor version 3 accepted by different tools.")
    required_params = parser.add_argument_group("required named arguments")
    required_params.add_argument("-i", action="store", dest="source_descriptor_file", type=str, help="OpenAPI descriptor to use as source.", required=True)
    parser.add_argument("-o", action="store", dest="output_file", help="File in which the generated content must be wrote.", required=False, default="/tmp/openapi-fixed.json")
    args = parser.parse_args()
    print(colored("[+] Fixing content...", "yellow"))
    openapi_fixed = fix(args.source_descriptor_file)
    if openapi_fixed is not None:
        print(colored(f"[+] Write file '{args.output_file}'...", "yellow"))
        with open(args.output_file, "w", encoding=DEFAULT_ENCODING) as f:
            f.write(openapi_fixed)
        print(colored(f"[V] Operation finished.", "green"))
