package config

import (
	"errors"
	"fmt"
	"net"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"time"

	"gopkg.in/yaml.v3"
)

// Field beschrijft één instelling die de webinterface, de API en BlueGit
// kunnen lezen en wijzigen. Alles wat in Fields staat, is overal hetzelfde
// instelbaar.
type Field struct {
	Key   string `json:"key"`
	Label string `json:"label"`
	Help  string `json:"help"`
	// Kind is duration, int of text.
	Kind string `json:"kind"`
	// Restart: pas na een herstart van kracht.
	Restart bool `json:"restart,omitempty"`
}

// Fields zijn de instelbare velden, in de volgorde van de webinterface.
var Fields = []Field{
	{Key: "public_url", Label: "Publiek adres", Help: "Waar BlueGit deze server bereikt, bijvoorbeeld http://backup.lan:8080.", Kind: "text"},
	{Key: "archive_interval", Label: "Archiefinterval", Help: "Zo vaak wordt de hele kopie gecomprimeerd opgeslagen (bijvoorbeeld 24h, 12h, 7d).", Kind: "duration"},
	{Key: "retention_days", Label: "Bewaartermijn (dagen)", Help: "Archieven ouder dan dit gaan weg. 0 = nooit op leeftijd. Het nieuwste blijft altijd staan.", Kind: "int"},
	{Key: "min_free_mb", Label: "Minimaal vrij (MB)", Help: "Minder vrije schijfruimte dan dit: het oudste archief gaat weg.", Kind: "int"},
	{Key: "rate_limit_kib", Label: "Downloadsnelheid (KiB/s)", Help: "Zo snel wordt BlueGit hoogstens gelezen. 0 = onbeperkt.", Kind: "int"},
	{Key: "full_sync_interval", Label: "Volledige controle", Help: "Ook zonder melding zo vaak alles nalopen.", Kind: "duration"},
	{Key: "min_sync_interval", Label: "Minimale tijd tussen syncs", Help: "Na een melding wacht de server minstens zo lang sinds de vorige sync.", Kind: "duration"},
	{Key: "listen", Label: "Luisteradres", Help: "Adres en poort van de webinterface en API. Geldt na een herstart.", Kind: "text", Restart: true},
}

// FieldByKey zoekt een veld.
func FieldByKey(key string) (Field, bool) {
	for _, f := range Fields {
		if f.Key == key {
			return f, true
		}
	}
	return Field{}, false
}

// Get geeft de waarde van key als tekst.
func (c Config) Get(key string) string {
	switch key {
	case "listen":
		return c.Listen
	case "public_url":
		return c.PublicURL
	case "data_dir":
		return c.DataDir
	case "archive_interval":
		return FormatDuration(c.ArchiveInterval.Duration)
	case "retention_days":
		return strconv.Itoa(c.RetentionDays)
	case "min_free_mb":
		return strconv.FormatInt(c.MinFreeMB, 10)
	case "rate_limit_kib":
		return strconv.FormatInt(c.RateLimitKiB, 10)
	case "full_sync_interval":
		return FormatDuration(c.FullSyncInterval.Duration)
	case "min_sync_interval":
		return FormatDuration(c.MinSyncInterval.Duration)
	}
	return ""
}

// FormatDuration schrijft 24h als "24h" en 30m als "30m".
func FormatDuration(d time.Duration) string {
	if d%(24*time.Hour) == 0 && d >= 48*time.Hour {
		return fmt.Sprintf("%dd", d/(24*time.Hour))
	}
	switch {
	case d == 0:
		return "0s"
	case d%time.Hour == 0:
		return fmt.Sprintf("%dh", d/time.Hour)
	case d%time.Minute == 0:
		return fmt.Sprintf("%dm", d/time.Minute)
	case d%time.Second == 0:
		return fmt.Sprintf("%ds", d/time.Second)
	}
	return d.String()
}

// ParseDuration leest een Go-duur of een aantal dagen ("7d").
func ParseDuration(s string) (time.Duration, error) {
	s = strings.TrimSpace(s)
	if strings.HasSuffix(s, "d") {
		n, err := strconv.Atoi(strings.TrimSuffix(s, "d"))
		if err == nil && n >= 0 {
			return time.Duration(n) * 24 * time.Hour, nil
		}
	}
	d, err := time.ParseDuration(s)
	if err != nil {
		return 0, fmt.Errorf("ongeldige duur %q", s)
	}
	return d, nil
}

// Set zet key op val. Alleen velden uit Fields.
func (c *Config) Set(key, val string) error {
	f, ok := FieldByKey(key)
	if !ok {
		return fmt.Errorf("onbekende instelling %q", key)
	}
	val = strings.TrimSpace(val)
	switch f.Kind {
	case "duration":
		d, err := ParseDuration(val)
		if err != nil {
			return fmt.Errorf("%s: %w", key, err)
		}
		switch key {
		case "archive_interval":
			c.ArchiveInterval.Duration = d
		case "full_sync_interval":
			c.FullSyncInterval.Duration = d
		case "min_sync_interval":
			c.MinSyncInterval.Duration = d
		}
	case "int":
		n, err := strconv.ParseInt(val, 10, 64)
		if err != nil || n < 0 {
			return fmt.Errorf("%s: geef een geheel getal van 0 of meer", key)
		}
		switch key {
		case "retention_days":
			c.RetentionDays = int(n)
		case "min_free_mb":
			c.MinFreeMB = n
		case "rate_limit_kib":
			c.RateLimitKiB = n
		}
	default:
		switch key {
		case "public_url":
			c.PublicURL = strings.TrimRight(val, "/")
		case "listen":
			if _, _, err := net.SplitHostPort(val); err != nil {
				return fmt.Errorf("listen: verwacht host:poort, bijvoorbeeld 0.0.0.0:8080")
			}
			c.Listen = val
		}
	}
	return nil
}

// Apply zet een reeks instellingen in één keer. Bij een fout verandert er niets.
func (c *Config) Apply(set map[string]string) error {
	next := *c
	keys := make([]string, 0, len(set))
	for k := range set {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, k := range keys {
		if err := next.Set(k, set[k]); err != nil {
			return err
		}
	}
	if err := next.Validate(); err != nil {
		return err
	}
	*c = next
	return nil
}

// SettingsFile bewaart wat via de webinterface, API of BlueGit is ingesteld.
// Het gaat boven config.yml, zodat config.yml van root mag blijven.
const SettingsFile = "settings.yml"

// LoadSettings leest data_dir/settings.yml (ontbreekt: leeg).
func LoadSettings(dataDir string) (map[string]string, error) {
	out := map[string]string{}
	b, err := os.ReadFile(filepath.Join(dataDir, SettingsFile))
	if errors.Is(err, os.ErrNotExist) {
		return out, nil
	}
	if err != nil {
		return nil, err
	}
	if err := yaml.Unmarshal(b, &out); err != nil {
		return nil, fmt.Errorf("%s: %w", SettingsFile, err)
	}
	return out, nil
}

// SaveSettings schrijft data_dir/settings.yml.
func SaveSettings(dataDir string, set map[string]string) error {
	b, err := yaml.Marshal(set)
	if err != nil {
		return err
	}
	b = append([]byte("# Door de webinterface, API of BlueGit ingesteld. Gaat boven config.yml.\n"), b...)
	tmp := filepath.Join(dataDir, SettingsFile+".tmp")
	if err := os.WriteFile(tmp, b, 0o600); err != nil {
		return err
	}
	return os.Rename(tmp, filepath.Join(dataDir, SettingsFile))
}
