package kubespray

import (
	"context"
	"io"
	"kube-forge/internal/config"
	"os"
	"path/filepath"

	"github.com/apenella/go-ansible/v2/pkg/execute"
	"github.com/apenella/go-ansible/v2/pkg/execute/stdoutcallback"
	"github.com/apenella/go-ansible/v2/pkg/playbook"
)

func getPlaybookParameters(tags string) playbook.AnsiblePlaybookOptions {
	cfg := config.GetConfig()

	ansiblePlaybookOptions := playbook.AnsiblePlaybookOptions{
		Inventory: filepath.Join(cfg.WorkDir, "kubespray/inventory/hosts"),
		Tags:      tags,
		User:      cfg.Credentials.User,
		Become:    true,
	}

	if cfg.Credentials.PrivateKeyFile != "" {
		ansiblePlaybookOptions.PrivateKey = cfg.Credentials.PrivateKeyFile
	}

	if cfg.Credentials.AskSudoPassword {
		ansiblePlaybookOptions.AskBecomePass = true
	}

	return ansiblePlaybookOptions
}

func CopyK8SAdminConfig(pathInDataDir string) {
	config := config.GetConfig()
	dataDir := config.WorkDir
	var adminDefaultConfigPath = filepath.Join(dataDir, "kubespray/inventory/artifacts/admin.conf")
	var adminOutConfigPath = filepath.Join(dataDir, pathInDataDir)
	source, err := os.Open(adminDefaultConfigPath)
	if err != nil {
		panic(err)
	}
	defer source.Close()

	destination, err := os.Create(adminOutConfigPath)
	if err != nil {
		panic(err)
	}
	defer destination.Close()
	_, err = io.Copy(destination, source)
	if err != nil {
		panic(err)
	}
}

func runPlaybook(playbookPath string, tags string) {
	config := config.GetConfig()
	var callbackExecute execute.Executor

	playbookOptions := getPlaybookParameters(tags)
	playbookCmd := playbook.NewAnsiblePlaybookCmd(
		playbook.WithPlaybooks(playbookPath),
		playbook.WithPlaybookOptions(&playbookOptions),
	)
	execute := execute.NewDefaultExecute(
		execute.WithCmd(playbookCmd),
		execute.WithErrorEnrich(playbook.NewAnsiblePlaybookErrorEnrich()),
	)

	if config.Verbose {
		callbackExecute = stdoutcallback.NewDebugStdoutCallbackExecute(execute)
	} else {
		callbackExecute = stdoutcallback.NewDenseStdoutCallbackExecute(execute)
	}

	err := callbackExecute.Execute(context.Background())
	if err != nil {
		panic(err)
	}
}
