import json
import random

def wait_for_user_input(name: str):
    while True:
        user_input = input(f"[?] {name}? (Y/N): ")
        if user_input.lower() == "y":
            print(f"[i] {name} ENABLED")
            return True
        elif user_input.lower() == "n":
            print(f"[i] {name} disabled")
            return False

def wait_for_user_start() -> bool:
    if automatic:
        return True
    else:
        return wait_for_user_input("Start")

def get_do_disable_first() -> bool:
    # This is probably unneeded...
    # I forgot why I put this in V1 so uhhh I'm too scared to take it out now
    if automatic:
        return False
    return wait_for_user_input("Disable all peers first")

def get_do_randomize() -> bool:
    if automatic:
        return do_randomize;
    return wait_for_user_input("Randomize ports")

def get_peer_selection(length: int) -> int:
    if automatic:
        return random.randint(0, length - 1)
    else:
        user_in = int(input("Select the target server [index] (-1 for random): "))
        if user_in == -1:
            return random.randint(0, length - 1)
        else:
            return user_in - 1  # Index starts at 1

def get_do_speedtest() -> bool:
    if automatic:
        return True # I guess this is what you are here for anyways
    else:
        return wait_for_user_input("Use speedtest to automatically select server")


def get_speedtest_threshold() -> float:
    """
    :returns in mbps.
    """
    return speedtest_threshold * 1000.0 * 1000.0

def get_gateway_name() -> str:
    return gateway_name


def genconfig(location:str) -> None:
    data = {
        "keepalive_interval": 25, # The keepalive_interval of your peers. There's no good way of retrieving this info from OPNSense last time I checked.
        "randomize_port_range": [[53, 53], [123, 123], [443, 443], [4000, 33433], [33565, 51820], [52001, 60000]], # Preset ranges for Mullvad. Inclusive.
        "instance_UUID": "[CHANGE ME]", # Find it via https://github.com/KipJM/OpnsenseMullvadPeerAdder/blob/master/config_and_run_me_first.py
        "opnsense_api": "[CHANGE ME, EXAMPLE: https://192.168.1.1/api]",
        "api_file": "api_key.txt",
        "debug": False,  # OPTIONAL. Shows debug info. Does not impact functionality.
        "automatic": False,  # OPTIONAL. Override all user input will preset values above.
        "speedtest_threshold": 25,  # in mbps. Once a peer reached at least this bandwidth the tool will stop searching any further
        "speedtest_maxtries": 5, # Max number of different peers to try before giving up.
        "gateway_name": "",  # OPTIONAL. Will attempt to reset the gateway watcher for this to remove the orange dot on the dashboard.
        "do_randomize": False,  # OPTIONAL. Randomize ports of all peers
        "verbose": False
    }
    with open(location, "w+") as f2:
        # load default values
        json.dump(data, f2)

    print(f"sample json generated at {location}. You need to modify some of its values.")


def load_config():
    global keepalive_interval, randomize_port_range, instance_UUID, opnsense_api, speedtest_threshold, speedtest_maxtries, debug, automatic, gateway_name, do_randomize, verbose, api_key, api_secret
    from . import cli_config

    with open(cli_config.config_path, "r") as f:
        data = json.load(f)
        if data == {}:
            print(
                "[ERR] CONFIG FILE DOES NOT EXIST/EMPTY. Generate a template config using: opnspeedguard --genconfig --config (where to output the file)")
            exit(-1)

    keepalive_interval = data["keepalive_interval"]  # Default: 25
    randomize_port_range = data[
        "randomize_port_range"]  # Mullvad allowed port ranges. You can remove any undesired port range here.
    instance_UUID = data["instance_UUID"]
    opnsense_api = data["opnsense_api"]
    speedtest_threshold = data["speedtest_threshold"]  # MB
    speedtest_maxtries = data["speedtest_maxtries"]

    # OPTIONALS
    debug = data.get("debug", False)
    automatic = data.get("automatic", False)
    gateway_name = data.get("gateway_name", "")
    do_randomize = data.get("do_randomize", False)
    verbose = data.get("verbose", False)

    # Read api key
    try:
        with open(cli_config.api_path) as f:
            api_key = f.readline().strip().removeprefix("key=")
            api_secret = f.readline().strip().removeprefix("secret=")
    except FileNotFoundError:
        print("[ERR] API KEY FILE NOT FOUND! Assign a valid api_key.txt generated by OPNSense!")
        exit(-1)


# == MAIN ===

keepalive_interval      = None
randomize_port_range    = None
instance_UUID           = ""
opnsense_api            = ""
speedtest_threshold     = None
speedtest_maxtries      = None
debug                   = False
automatic               = False
gateway_name            = ""
do_randomize            = False
verbose                 = False
api_key                 = ""
api_secret              = ""