package bridge

import (
	"encoding/json"
	"errors"
	"os"
	"path/filepath"
	"strings"
)

const (
	DefaultControlURL      = "https://sdp.mm.md"
	DefaultControllerInput = DefaultControlURL
)

type configState struct {
	ControllerInput string `json:"controllerInput,omitempty"`
	AuthKey         string `json:"authKey,omitempty"`
}

func defaultConfigPath() (string, error) {
	base, err := os.UserConfigDir()
	if err != nil {
		return "", err
	}
	return filepath.Join(base, "Mirage", "mirage-ui.json"), nil
}

func normalizeControllerInput(input string) string {
	input = strings.TrimSpace(input)
	if input == "" {
		return DefaultControllerInput
	}
	return input
}

func controlURLForControllerInput(input string) string {
	input = normalizeControllerInput(input)
	if strings.HasPrefix(input, "http://") || strings.HasPrefix(input, "https://") {
		return input
	}
	controlURL := "https://sdp." + input
	if !strings.Contains(input, ".") {
		controlURL += ".com"
	}
	return controlURL
}

func loadConfig(path string) (configState, error) {
	data, err := os.ReadFile(path)
	switch {
	case err == nil:
	case errors.Is(err, os.ErrNotExist):
		return configState{}, nil
	default:
		return configState{}, err
	}
	var state configState
	if err := json.Unmarshal(data, &state); err != nil {
		return configState{}, err
	}
	return state, nil
}

func saveConfig(path string, state configState) error {
	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
		return err
	}
	data, err := json.MarshalIndent(state, "", "  ")
	if err != nil {
		return err
	}
	data = append(data, '\n')
	return os.WriteFile(path, data, 0o600)
}
