import os
import yaml
import shutil
import subprocess
import sys
import requests

# folder paths
server_list_path = "./servers.yml"
builder_path = "./builder"
builder_octoprint_config_path = f"{builder_path}/octoprint/octoprint/config.yaml"

def create_folder_if_not_exists(folder_path):
  if not os.path.exists(folder_path):
    os.makedirs(folder_path)

def copy_folder(source_folder, destination_folder):
  try:
    if os.path.exists(destination_folder):
      shutil.rmtree(destination_folder)

    shutil.copytree(source_folder, destination_folder)
  except Exception as e:
    print(f"Error copying folder: {e}")

def copy_file(source_file, destination_file):
  try:
    shutil.copy(source_file, destination_file)
  except Exception as e:
    print(f"Error copying file: {e}")


create_folder_if_not_exists(builder_path)
copy_file("./template/server-template/Dockerfile", "./builder/")

# read servers and octoprint template config

with open(server_list_path, 'r') as server_list_file:
  server_list = yaml.safe_load(server_list_file)

# update docker-compose in builder folder for each server in servers.yml

def run_docker_compose_up():
  try:
    subprocess.run(['docker', 'compose', 'up', '-d'], cwd='./builder/', check=True)
  except subprocess.CalledProcessError as e:
    print(f"Error executing 'docker-compose up': {e}")

def update_config_recursive(base_config, update_config):
  for key, value in update_config.items():
    if isinstance(value, dict):
      if key in base_config and isinstance(base_config[key], dict):
        update_config_recursive(base_config[key], value)
      else:
        base_config[key] = value  # Füge die gesamte neue Verschachtelung hinzu, falls noch nicht vorhanden
    else:
      base_config[key] = value

def replace_octoprint_config(server):
  with open(builder_octoprint_config_path, 'r') as file:
    config = yaml.safe_load(file)

  update_config_recursive(config, server['octoprint_config'])

  with open(builder_octoprint_config_path, 'w') as file:
    yaml.dump(config, file)


def replace_servers_yml(server, index):
  # set auth token if not exists for the server
  if ("octoprint_config" not in server or 
    "plugins" not in server["octoprint_config"] or 
    "obico" not in server["octoprint_config"]["plugins"]):
    if "octoprint_config" not in server_list["servers"][index]:
      server_list["servers"][index]["octoprint_config"] = {}

    if "plugins" not in server_list["servers"][index]["octoprint_config"]:
      server_list["servers"][index]["octoprint_config"]["plugins"] = {}

    if "obico" not in server_list["servers"][index]["octoprint_config"]["plugins"]:
      server_list["servers"][index]["octoprint_config"]["plugins"]["obico"] = {}

    # ask the user for the verify code which he gets from the obico add printer website

    server_name = server["name"]
    verify_code = input(f"Enter the 6-digit verification code for printer: {server_name}: ")

    # request to obico server to get the auth token by sending the verify code

    obico_server_url = server_list["obico_server_url"]
    response = requests.get(f"{obico_server_url}/api/v1/octo/verify/?code={verify_code}")

    if response.status_code == 200:
      # set auth_token for the obico plugin
      server_list["servers"][index]["octoprint_config"]["plugins"]["obico"]["auth_token"] = response.json()["printer"]["auth_token"]

      # save servers.yml
      with open(server_list_path, 'w') as file:
        yaml.dump(server_list, file)
    else:
      print("Error. Access code not valid: Response status code:", response.status_code)
      sys.exit(0)


for index, server in enumerate(server_list['servers']):
  copy_folder("./template/octoprint/", "./builder/octoprint/")

  replace_servers_yml(server, index)

  # update the docker-compose.yml
  with open('./template/server-template/docker-compose.yml', 'r') as file:
    file_content = file.read()

  file_content = file_content.replace('{{NAME}}', server['name'])
  file_content = file_content.replace('{{PORT}}', str(server['port']))
  file_content = file_content.replace('{{PORT_MJPEG}}', str(server['port_mjpeg']))  

  """
  file_content = file_content.replace('{{BAMBU_CODE}}', str(server['bambu_access_code']))  
  file_content = file_content.replace('{{BAMBU_IP}}', str(server['bambu_ip'])) """

  file_content = file_content.replace('{{BAMBU_CODE}}', server['octoprint_config']['plugins']['bambu_printer']['access_code'])
  file_content = file_content.replace('{{BAMBU_IP}}', server['octoprint_config']['plugins']['bambu_printer']['host'])

  with open(f'{builder_path}/docker-compose.yml', 'w') as file:
    file.write(file_content)

  replace_octoprint_config(server)

  run_docker_compose_up()
  """
  thread = threading.Thread(target=run_docker_compose_up)
  thread.start()
  """

  # time.sleep(5)