package util

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"strings"

	m "git.k-space.ee/k-space/logmower-shipper/pkg/mongo"
)

func ParseLogFilename(name string) (i m.KubeInfo, ok bool) {
	name = filepath.Base(name)

	// https://github.com/kubernetes/design-proposals-archive/blob/8da1442ea29adccea40693357d04727127e045ed/node/kubelet-cri-logging.md
	// <pod_name>_<pod_namespace>_<container_name>-<container_id>.log`

	i.Pod, name, ok = strings.Cut(name, "_")
	if !ok {
		return
	}

	i.Namespace, name, ok = strings.Cut(name, "_")
	if !ok {
		return
	}

	i.ContainerName, name, ok = strings.Cut(name, "-")
	if !ok {
		return
	}

	i.ContainerId = strings.TrimSuffix(name, ".log")
	if !strings.HasSuffix(name, ".log") {
		return
	}

	return i, true
}

func Hostinfo(nodeName string) (h m.Host, err error) {
	if nodeName == "" {
		nodeName, err = os.Hostname()
		if err != nil {
			return h, fmt.Errorf("getting hostname: %w", err)
		}
	}

	h.Name = strings.TrimSpace(nodeName)

	id, err := os.ReadFile("/etc/machine-id")
	if err != nil {
		return h, fmt.Errorf("getting machineId: %w", err)
	}

	h.Id = strings.TrimSpace(string(id))

	h.Arch = runtime.GOARCH

	return h, nil
}
