import json
import os
import sys
import time
from time import sleep

import requests
import urllib3
from deepsecurity.rest import ApiException
from rich.console import Console

from dsmigrator.api_config import AMConfigApiInstance
from dsmigrator.logging import log
from dsmigrator.migrator_utils import (
    safe_list_get,
    safe_request,
    validate_create,
    validate_create_dict,
)

cert = False


def json_to_list(json_item, key, outlist):
    item = json_item.get(key)
    if item:
        outlist.append(str(item))
        return outlist


def am_config_transform(antimalwareconfig, OLD_HOST, OLD_API_KEY):
    amdirectorylist, amfileextentionlist, amfilelist, allamconfig = AMconfigtenant1(
        antimalwareconfig, OLD_HOST, OLD_API_KEY
    )
    return amdirectorylist, amfileextentionlist, amfilelist, allamconfig


def am_validate_create(
    allofpolicy,
    antimalwareconfig,
    allamconfig,
    amdirectorylist,
    amalldirectorynew,
    amfileextentionlist,
    amallfileextentionnew,
    amfilelist,
    amallfilelistnew,
    schedule_id_dict,
    NEW_HOST,
    NEW_API_KEY,
):
    mod_allamconfig = AmConfigCheck(
        allamconfig,
        amdirectorylist,
        amalldirectorynew,
        amfileextentionlist,
        amallfileextentionnew,
        amfilelist,
        amallfilelistnew,
    )

    allamconfigdict = AmconfigTenant2(mod_allamconfig, NEW_API_KEY)

    aop_replace_am_configs = AmReplaceConfig(
        allofpolicy, allamconfigdict, schedule_id_dict
    )
    final = aop_replace_am_configs
    return final


def AMconfigtenant1(antimalwareconfig, url_link_final, tenant1key):
    allamconfig = []
    directorylist = []
    fileextentionlist = []
    filelist = []
    log.info("Getting Anti-Malware configuration from Tenant 1")
    for count, amconfig in enumerate(antimalwareconfig):
        if int(amconfig) != 0:
            url = url_link_final + "api/antimalwareconfigurations/" + str(amconfig)
            response = safe_request(tenant1key, "GET", url, payload={}, cert=cert)
            describe = str(response.text)
            allamconfig.append(describe)
            describe_json = json.loads(describe)
            json_to_list(describe_json, "directoryListID", directorylist)
            json_to_list(describe_json, "excludedDirectoryListID", directorylist)
            json_to_list(
                describe_json, "excludedFileExtensionListID", fileextentionlist
            )
            json_to_list(describe_json, "fileExtensionListID", fileextentionlist)
            json_to_list(describe_json, "excludedFileListID", filelist)
            json_to_list(describe_json, "fileListID", filelist)
            json_to_list(describe_json, "excludedProcessImageFileListID", filelist)
            log.info(
                "#" + str(count) + " Anti-Malware Config ID: " + str(amconfig),
            )
    directorylist = list(dict.fromkeys(directorylist))
    fileextentionlist = list(dict.fromkeys(fileextentionlist))
    filelist = list(dict.fromkeys(filelist))
    return directorylist, fileextentionlist, filelist, allamconfig


def AmconfigTenant2(allamconfig, NEW_API_KEY):
    log.info("Creating Anti-Malware Configuration in Tenant2")
    if allamconfig:
        allamconfigdict = validate_create_dict(
            allamconfig, AMConfigApiInstance(NEW_API_KEY), "anti malware"
        )
    log.info("New AM Config Dict")
    log.info(allamconfigdict)
    allamconfigdict[0] = 0
    return allamconfigdict


def AmReplaceConfig(allofpolicy, allamconfigdict, schedule_id_dict):
    count = 0
    for describe in allofpolicy:

        def replace_am_id(
            type,
            policy_json_string,
            newiddict,
        ):
            policy_json = json.loads(policy_json_string)
            policy_am_json = policy_json["antiMalware"]
            oldid = policy_am_json[type]
            policy_am_json[type] = newiddict[oldid]
            final_json = json.dumps(policy_json)
            return final_json

        describe_rt = replace_am_id(
            "realTimeScanConfigurationID", describe, allamconfigdict
        )
        describe_man = replace_am_id(
            "manualScanConfigurationID", describe_rt, allamconfigdict
        )
        describe_sch = replace_am_id(
            "scheduledScanConfigurationID", describe_man, allamconfigdict
        )
        describe_rt_sch = replace_am_id(
            "realTimeScanScheduleID", describe_sch, schedule_id_dict
        )
        allofpolicy[count] = describe_rt_sch
        count = count + 1
    return allofpolicy


def AmConfigCheck(
    allamconfig,
    directorylist,
    alldirectorynew,
    fileextentionlist,
    allfileextentionnew,
    filelist,
    allfilelistnew,
):

    new_allamconfig = []
    dir_list_dict = {
        int(directorylist[i]): int(safe_list_get(alldirectorynew, i))
        for i in range(len(directorylist))
    }
    file_list_dict = {
        int(filelist[i]): int(safe_list_get(allfilelistnew, i))
        for i in range(len(filelist))
    }
    file_ext_dict = {
        int(fileextentionlist[i]): int(safe_list_get(allfileextentionnew, i))
        for i in range(len(fileextentionlist))
    }
    for amconfig in allamconfig:

        def id_replacer(json: dict, rosetta: dict, key: str) -> dict:
            oldid = json.get(key)
            newid = rosetta.get(oldid)
            if newid is not None:
                json[key] = newid
            return json

        amconfig_json = json.loads(amconfig)

        amconfig_json = id_replacer(amconfig_json, dir_list_dict, "directoryListID")
        amconfig_json = id_replacer(
            amconfig_json, dir_list_dict, "excludedDirectoryListID"
        )
        amconfig_json = id_replacer(amconfig_json, file_ext_dict, "fileExtensionListID")
        amconfig_json = id_replacer(
            amconfig_json, file_ext_dict, "excludedFileExtensionListID"
        )
        amconfig_json = id_replacer(amconfig_json, file_list_dict, "excludedFileListID")
        amconfig_json = id_replacer(
            amconfig_json, file_list_dict, "excludedProcessImageFileListID"
        )
        new_amconfig = json.dumps(amconfig_json)
        new_allamconfig.append(new_amconfig)
    return new_allamconfig


def RenameAmConfig(allamconfig):
    count = 0
    if allamconfig:
        for describe in allamconfig:
            amjson = json.loads(describe)
            log.info(describe)
            amjson["name"] = amjson["name"] + " - Migrated"
            allamconfig[count] = json.dumps(amjson)
            count = count + 1
    return allamconfig
