package segments

import (
	"errors"
	"strings"

	"github.com/jandedobbeleer/oh-my-posh/src/segments/options"
)

type CfTarget struct {
	Base

	CfTargetDetails
}

type CfTargetDetails struct {
	URL   string
	User  string
	Org   string
	Space string
}

func (c *CfTarget) Template() string {
	return "{{if .Org }}{{ .Org }}{{ end }}{{if .Space }}/{{ .Space }}{{ end }}"
}

func (c *CfTarget) Enabled() bool {
	if !c.env.HasCommand("cf") {
		return false
	}

	displayMode := c.options.String(DisplayMode, DisplayModeAlways)
	if displayMode != DisplayModeFiles {
		return c.setCFTargetStatus()
	}

	files := c.options.StringArray(options.Files, []string{"manifest.yml"})
	for _, file := range files {
		manifest, err := c.env.HasParentFilePath(file, false)
		if err != nil || manifest.IsDir {
			continue
		}

		return c.setCFTargetStatus()
	}

	return false
}

func (c *CfTarget) setCFTargetStatus() bool {
	output, err := c.getCFTargetCommandOutput()

	if err != nil {
		return false
	}

	lines := strings.SplitSeq(output, "\n")
	for line := range lines {
		key, value, found := strings.Cut(line, ":")
		if !found {
			continue
		}
		value = strings.TrimSpace(value)
		switch key {
		case "API endpoint":
			c.URL = value
		case "user":
			c.User = value
		case "org":
			c.Org = value
		case "space":
			c.Space = value
		}
	}

	return true
}

func (c *CfTarget) getCFTargetCommandOutput() (string, error) {
	output, err := c.env.RunCommand("cf", "target")

	if err != nil {
		return "", err
	}

	if output == "" {
		return "", errors.New("cf command output is empty")
	}

	return output, nil
}
