import requests
import json
import logging
import os
import datetime
import urllib3
import argparse
import gc
from http import HTTPStatus

class ImportReportHandler:
    def __init__(self, tenant_aapi_url: str, aapi_token: str, report_history_days: int):
        self.AAPI_URL = tenant_aapi_url
        self.AAPI_TOKEN = aapi_token
        self.report_history_days = report_history_days
        urllib3.disable_warnings()
        self.LOG_DIR = 'log'
        log_file_name = f"{self.LOG_DIR}{os.sep}import_report_{datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')}.log"
        if not os.path.exists(self.LOG_DIR):
            os.makedirs(self.LOG_DIR)
        logging.basicConfig(
            filename=log_file_name,
            format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
            level=logging.DEBUG)
        logging.log(level=logging.INFO, msg="Starting Report Procedure.")

        if self.AAPI_URL is None or len(self.AAPI_URL) == 0:
            self.AAPI_URL = input("Enter Tenant AAPI URL: \n")
        if self.AAPI_TOKEN is None or len(self.AAPI_TOKEN) == 0:
            self.AAPI_TOKEN = input("Enter Tenant AAPI Token: \n")

        # Remove trailing slash from AAPI URL to avoid double slashes
        self.AAPI_URL = self.AAPI_URL.rstrip('/')
        self.is_saas = '.com' in self.AAPI_URL
        if self.is_saas:
            self.AAPI_URL = self.AAPI_URL + "/automation-api"
        self.report_url = self.AAPI_URL + "/config/data-platform"
        if self.is_saas:
            self.headers = {
                'x-api-key': self.AAPI_TOKEN,
                'Content-Type': 'application/json'
            }
        else:
            self.headers = {
                'Authorization': f'Bearer {self.AAPI_TOKEN}',
                'Content-Type': 'application/json'
            }

    def run(self):

        http_response = requests.get(url=self.report_url + "/inject/report?reportHistoryDays=" + str(self.report_history_days), headers=self.headers, verify=False)
        logging.log(level=logging.INFO, msg=f"Response : \n{http_response.text}")
        if http_response.status_code != HTTPStatus.OK:
            raise Exception(http_response.text)
        http_response_text_as_json = json.loads(http_response.text)
        pp_response = json.dumps(http_response_text_as_json, indent=4)
        logging.log(level=logging.INFO, msg=f"Report : \n{pp_response}")
        print(f"{pp_response}\n", end="")




if __name__ == '__main__':
    try:
        # Required command line arguments for the import script:
        parser = argparse.ArgumentParser(description="Control-M Workload Archiving data migration"
                                                     " into Control-M SaaS export script's args parser")
        parser.add_argument('--tenant_aapi_url', required=True, type=str, help="Control-M SaaS Tenant's AAPI url")
        parser.add_argument('--aapi_token', required=True, type=str, help="Control-M SaaS Tenant AAPI token")
        parser.add_argument('--report_history_days', required=False, type=int, default=7,
                            help="Report days range (default is 7 days)")
        parser.add_argument('--python_exe', required=False, default='python3', type=str,
                            help="The python interpreter name")

        # Parse the command-line arguments:
        args = parser.parse_args()
        tenant_aapi_url = args.tenant_aapi_url
        aapi_token = args.aapi_token
        report_history_days = args.report_history_days

        import_report_handler = ImportReportHandler(tenant_aapi_url, aapi_token, report_history_days)
        import_report_handler.run()
        gc.collect()
        exit(0)
    except Exception as e:
        err_msg = "Exception was occurred during Control-M Workload Archiving Import status script, \n" \
                  f"the exception message is: {str(e)}"
        print(err_msg)
        gc.collect()
        exit(2)

