// Copyright 2025 Emiliano Spinella (eminwux)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

package config

import (
	"os"
	"path/filepath"

	"github.com/spf13/cobra"
)

func DefaultRunPath() string {
	return filepath.Join("/", "opt", "kukeon")
}

func GetRunPathFromEnvAndFlags(cmd *cobra.Command, viperKey string) (string, error) {
	runPath, _ := cmd.Flags().GetString("run-path")
	if runPath == "" {
		if env := os.Getenv(viperKey); env != "" {
			runPath = env
		} else {
			// final fallback: same default you use at runtime
			runPath = DefaultRunPath()
		}
	}
	return runPath, nil
}

func GetProfilesFileFromEnvAndFlags(cmd *cobra.Command, viperKey string) (string, error) {
	profilesFile, _ := cmd.Flags().GetString("profiles-file")
	if profilesFile == "" {
		if env := os.Getenv(viperKey); env != "" {
			profilesFile = env
		} else {
			// final fallback: same default you use at runtime
			profilesFile = DefaultProfilesFile()
		}
	}
	return profilesFile, nil
}

func DefaultProfilesFile() string {
	base, err := os.UserHomeDir()
	if err != nil {
		// fallback to tmp if home dir cannot be determined
		base = "tmp"
	}

	return filepath.Join(base, ".kukeon", "profiles.yaml")
}

// DefaultServerConfigurationFile is the on-disk path the kukeond daemon and
// `kuke init` read when the user does not pass `--configuration` or
// `--server-configuration`. An absent file is not an error — the daemon
// falls back to its hardcoded defaults.
func DefaultServerConfigurationFile() string {
	return filepath.Join("/", "etc", "kukeon", "kukeond.yaml")
}

// DefaultKukeDir is the per-operator kuke state directory (~/.kuke) holding
// the client configuration, the team-distribution global-facts file
// (kuketeams.yaml), and the per-project drop-in directory (kuketeam.d/). Falls
// back to "tmp" when the home directory cannot be determined, matching the
// other default-path helpers.
func DefaultKukeDir() string {
	base, err := os.UserHomeDir()
	if err != nil {
		// fallback to tmp if home dir cannot be determined
		base = "tmp"
	}
	return filepath.Join(base, ".kuke")
}

// DefaultClientConfigurationFile is the on-disk path the `kuke` client reads
// when the user does not pass `--configuration`. An absent file is not an
// error — the client falls back to its hardcoded defaults.
func DefaultClientConfigurationFile() string {
	return filepath.Join(DefaultKukeDir(), "kuke.yaml")
}
