package workflow_builder

import (
	"encoding/json"
	"fmt"
	"net/http"
	"slices"
	"time"

	oclib "cloud.o-forge.io/core/oc-lib"
	"cloud.o-forge.io/core/oc-lib/logs"
	"cloud.o-forge.io/core/oc-lib/models/peer"
	tools "cloud.o-forge.io/core/oc-lib/tools"
)


type AdmiraltySetter struct {
	Id			string				// ID to identify the execution, correspond to workflow_executions id
	NodeName 	string	// Allows to retrieve the name of the node used for this execution on each peer {"peerId": "nodeName"}
}

func (s *AdmiraltySetter) InitializeAdmiralty(localPeerID string,remotePeerID string) error {
	
	logger := logs.GetLogger()

	data := oclib.NewRequest(oclib.LibDataEnum(oclib.PEER),"",localPeerID,nil,nil).LoadOne(remotePeerID)
	if data.Code != 200 {
		logger.Error().Msg("Error while trying to instantiate remote peer " + remotePeerID)
		return fmt.Errorf(data.Err)
	}
	remotePeer := data.ToPeer()

			data = oclib.NewRequest(oclib.LibDataEnum(oclib.PEER),"",localPeerID,nil,nil).LoadOne(localPeerID)
			if data.Code != 200 {
				logger.Error().Msg("Error while trying to instantiate local peer " + remotePeerID)
				return fmt.Errorf(data.Err)
			}
			localPeer := data.ToPeer()

			caller := tools.NewHTTPCaller(
				map[tools.DataType]map[tools.METHOD]string{
					tools.ADMIRALTY_SOURCE: {
						tools.POST :"/:id",
					},
					tools.ADMIRALTY_KUBECONFIG: {
						tools.GET:"/:id",
					},
					tools.ADMIRALTY_SECRET: {
						tools.POST:"/:id",
					},
					tools.ADMIRALTY_TARGET: {
						tools.POST:"/:id",
					},
					tools.ADMIRALTY_NODES: {
						tools.GET:"/:id",
					},
			tools.ADMIRALTY_TARGET: {
					tools.POST:"/:id",
				},
				tools.ADMIRALTY_NODES: {
					tools.GET:"/:id",
				},
			},
		)

	logger.Info().Msg(" Creating the Admiralty Source on " + remotePeerID + " ns-" + s.Id + "\n\n")
	_ = s.callRemoteExecution(remotePeer, []int{http.StatusCreated, http.StatusConflict},caller, s.Id, tools.ADMIRALTY_SOURCE, tools.POST, nil, true)
	logger.Info().Msg(" Retrieving kubeconfig with the secret on " + remotePeerID + " ns-" + s.Id + "\n\n")
	kubeconfig := s.getKubeconfig(remotePeer, caller)
	logger.Info().Msg(" Creating a secret from the kubeconfig " + localPeerID + " ns-" + s.Id + "\n\n")
	_ = s.callRemoteExecution(localPeer, []int{http.StatusCreated}, caller,s.Id, tools.ADMIRALTY_SECRET, tools.POST,kubeconfig, true)
	logger.Info().Msg(" Creating the Admiralty Target on " + localPeerID + " ns-" + s.Id + "\n\n")
	_ = s.callRemoteExecution(localPeer,[]int{http.StatusCreated, http.StatusConflict},caller,s.Id,tools.ADMIRALTY_TARGET,tools.POST, nil, true)
	logger.Info().Msg(" Checking for the creation of the admiralty node on " + localPeerID + " ns-" + s.Id + "\n\n")
	s.checkNodeStatus(localPeer,caller)
	
	return nil
}

func (s *AdmiraltySetter) getKubeconfig(peer *peer.Peer, caller *tools.HTTPCaller) map[string]string {
	var kubedata map[string]string
	_ = s.callRemoteExecution(peer, []int{http.StatusOK}, caller, s.Id, tools.ADMIRALTY_KUBECONFIG, tools.GET, nil, true)
	if caller.LastResults["body"] == nil || len(caller.LastResults["body"].([]byte)) == 0 {
		fmt.Println("Something went wrong when retrieving data from Get call for kubeconfig")
		panic(0)
	}
	err := json.Unmarshal(caller.LastResults["body"].([]byte), &kubedata)
	if err != nil {
		fmt.Println("Something went wrong when unmarshalling data from Get call for kubeconfig")
		panic(0)
	}

	return kubedata
}

func (*AdmiraltySetter) callRemoteExecution(peer *peer.Peer, expectedCode []int,caller *tools.HTTPCaller, dataID string, dt tools.DataType, method tools.METHOD, body interface{}, panicCode bool) *peer.PeerExecution {
	resp, err := peer.LaunchPeerExecution(peer.UUID, dataID, dt, method, body, caller)
	if err != nil {
		fmt.Println("Error when executing on peer at", peer.Url)
		fmt.Println(err)
		panic(0)
	}

	if !slices.Contains(expectedCode, caller.LastResults["code"].(int)) {
		fmt.Println("Didn't receive the expected code :", caller.LastResults["code"], "when expecting", expectedCode)
		if _, ok := caller.LastResults["body"]; ok {
			logger.Info().Msg(string(caller.LastResults["body"].([]byte)))
			// fmt.Println(string(caller.LastResults["body"].([]byte)))
		}
		if panicCode {
			panic(0)
		}
	}

	return resp
}

func (s *AdmiraltySetter) storeNodeName(caller *tools.HTTPCaller){
	var data map[string]interface{}
	if resp, ok := caller.LastResults["body"]; ok {
		json.Unmarshal(resp.([]byte), &data)
	}

	if node, ok := data["node"]; ok {
		metadata := node.(map[string]interface{})["metadata"]
		name := metadata.(map[string]interface{})["name"].(string)
		s.NodeName = name
	} else {
		fmt.Println("Could not retrieve data about the recently created node")
		panic(0)
	}
}

func (s *AdmiraltySetter) checkNodeStatus(localPeer *peer.Peer, caller *tools.HTTPCaller){
	for i := range(5) {
		time.Sleep(5 * time.Second) // let some time for kube to generate the node
		_ = s.callRemoteExecution(localPeer,[]int{http.StatusOK},caller,s.Id,tools.ADMIRALTY_NODES,tools.GET, nil, false)
		if caller.LastResults["code"] == 200 {
			s.storeNodeName(caller)
			return
		}
		if i == 5 {
			logger.Error().Msg("Node on " + localPeer.Name + " was never found, panicking !")
			panic(0)
		}
		logger.Info().Msg("Could not verify that node is up. Retrying...")
	}
	
}