// Package config leest het YAML-configuratiebestand van BlueGit.
package config

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

	"gitlab.com/Timfa/bluegit/internal/apppaths"
	"gitlab.com/Timfa/bluegit/internal/images"
	"gitlab.com/Timfa/bluegit/internal/realip"
	"gopkg.in/yaml.v3"
)

// Config is de installatie op de mini-PC.
type Config struct {
	BaseURL string `yaml:"base_url"`
	Listen  string `yaml:"listen"`
	// StatePath is de kleine map met database, sleutel en het gekozen
	// opslagpad. Leeg wordt /var/lib/bluegit, of %LOCALAPPDATA%\BlueGit op Windows.
	StatePath string `yaml:"state_path"`
	// StoragePath is optioneel. Leeg betekent dat de beheerder het pad
	// in de webinterface kiest. Er is geen standaardpad.
	StoragePath string `yaml:"storage_path"`
	// CachePath is de optionele leescache (bij voorkeur op een SSD).
	// Leeg betekent geen cache. Beheer kan het overschrijven.
	CachePath      string   `yaml:"cache_path"`
	CacheMaxMB     int64    `yaml:"cache_max_mb"`
	TrustedProxies []string `yaml:"trusted_proxies"`
	// BehindProxy is het oude veld. Het wordt geweigerd: één boolean
	// vertrouwt ofwel iedereen, ofwel niemand. De lijst hierboven beslist.
	BehindProxy bool   `yaml:"behind_proxy"`
	Auth        Auth   `yaml:"auth"`
	Git         Git    `yaml:"git"`
	SSH         SSH    `yaml:"ssh"`
	Runner      Runner `yaml:"runner"`
	CI          CI     `yaml:"ci"`

	proxies *realip.Set
}

// Auth wijst naar auth.timfalken.com, Microsoft Entra ID, of de lokale ontwikkelmodus.
type Auth struct {
	Mode             string `yaml:"mode"` // oauth | entra | dev
	BaseURL          string `yaml:"base_url"`
	ClientID         string `yaml:"client_id"`
	ClientSecret     string `yaml:"client_secret"`
	ClientSecretFile string `yaml:"client_secret_file"`
	RedirectPath     string `yaml:"redirect_path"`
	UserAgent        string `yaml:"user_agent"`
	DevUser          string `yaml:"dev_user"`
	DevAuthID        int64  `yaml:"dev_auth_id"`
	// TenantID is verplicht bij mode entra (directory-/tenant-id).
	TenantID string `yaml:"tenant_id"`
	// Issuer overschrijft de Entra-issuer. Leeg: login.microsoftonline.com/{tenant}/v2.0.
	// Voor tests of andere clouds (bijv. login.microsoftonline.us).
	Issuer string `yaml:"issuer"`
}

// Git wijst naar de git-binary en de standaardbranch van nieuwe repositories.
type Git struct {
	Binary        string `yaml:"binary"`
	DefaultBranch string `yaml:"default_branch"`
	HookBinary    string `yaml:"hook_binary"`
	// MaintenanceInterval is hoe vaak bare repositories onderhouden worden
	// (git maintenance of git gc --auto). Leeg is 24h. "off" of "0" zet uit.
	// Gebruik een Go-duur (24h, 168h) of een aantal dagen (7d).
	MaintenanceInterval string `yaml:"maintenance_interval"`
}

// DefaultMaintenanceInterval is de standaard: elke nacht.
const DefaultMaintenanceInterval = 24 * time.Hour

// MaintenanceEvery geeft het interval en of onderhoud aan staat.
func (g Git) MaintenanceEvery() (time.Duration, bool, error) {
	return ParseMaintenanceInterval(g.MaintenanceInterval)
}

// ParseMaintenanceInterval leest een duur. Leeg wordt 24 uur.
func ParseMaintenanceInterval(s string) (time.Duration, bool, error) {
	s = strings.TrimSpace(strings.ToLower(s))
	if s == "" {
		return DefaultMaintenanceInterval, true, nil
	}
	if s == "off" || s == "false" || s == "no" {
		return 0, false, nil
	}
	if s == "0" || s == "0s" || s == "0h" || s == "0d" {
		return 0, false, nil
	}
	if strings.HasSuffix(s, "d") {
		n, err := strconv.Atoi(strings.TrimSuffix(s, "d"))
		if err != nil || n <= 0 {
			return 0, false, fmt.Errorf("ongeldig maintenance_interval %q", s)
		}
		return time.Duration(n) * 24 * time.Hour, true, nil
	}
	d, err := time.ParseDuration(s)
	if err != nil {
		return 0, false, fmt.Errorf("ongeldig maintenance_interval %q", s)
	}
	if d <= 0 {
		return 0, false, nil
	}
	return d, true, nil
}

// SSH is de git-over-SSH-listener en het adres dat in clone-URL's staat.
// Listen is waar dit proces bindt. PublicHost en PublicPort zijn wat
// een gebruiker ziet; de ingress kan daar een andere poort voor gebruiken.
type SSH struct {
	Enabled    bool   `yaml:"enabled"`
	Listen     string `yaml:"listen"`
	PublicHost string `yaml:"public_host"`
	PublicPort int    `yaml:"public_port"`
}

// Runner is de ingebouwde Docker-runner.
type Runner struct {
	Name string `yaml:"name"`
}

// CI stuurt de Docker-runner.
type CI struct {
	Enabled     bool   `yaml:"enabled"`
	Docker      string `yaml:"docker_binary"`
	Concurrency int    `yaml:"concurrency"`
	Network     string `yaml:"network"`
	TimeoutSec  int    `yaml:"timeout_seconds"`
	// UpdateMaxWaitMin: zo lang wacht een self-update op lopende jobs
	// (en houdt nieuwe pipelines vast). Standaard 30.
	UpdateMaxWaitMin int                     `yaml:"update_max_wait_minutes"`
	Presets          map[string]PresetConfig `yaml:"presets"`
}

// PresetConfig is één image-alias. image mapt direct. dockerfile wordt
// door Steve gebouwd. from herschrijft de eerste FROM van een Dockerfile.
type PresetConfig struct {
	Image      string `yaml:"image"`
	Dockerfile string `yaml:"dockerfile"`
	From       string `yaml:"from"`
}

// ImageOverrides is de vorm die de runner en de infopagina lezen.
func (c CI) ImageOverrides() map[string]images.Override {
	if len(c.Presets) == 0 {
		return nil
	}
	out := make(map[string]images.Override, len(c.Presets))
	for name, p := range c.Presets {
		out[name] = images.Override{Image: p.Image, Dockerfile: p.Dockerfile, From: p.From}
	}
	return out
}

// Load leest path en vult ontbrekende waarden aan.
func Load(path string) (Config, error) {
	raw, err := os.ReadFile(path)
	if err != nil {
		return Config{}, fmt.Errorf("config lezen: %w", err)
	}
	var c Config
	if err := yaml.Unmarshal(raw, &c); err != nil {
		return Config{}, fmt.Errorf("config: %w", err)
	}
	c.applyDefaults()
	if v := os.Getenv("BLUEGIT_STATE_PATH"); v != "" {
		c.StatePath = v
	}
	if v := os.Getenv("BLUEGIT_STORAGE_PATH"); v != "" {
		c.StoragePath = v
	}
	if v := os.Getenv("BLUEGIT_CACHE_PATH"); v != "" {
		c.CachePath = v
	}
	if v := os.Getenv("BLUEGIT_LISTEN"); v != "" {
		c.Listen = v
	}
	if v := os.Getenv("BLUEGIT_AUTH_CLIENT_SECRET"); v != "" {
		c.Auth.ClientSecret = v
	}
	if c.Auth.ClientSecret == "" && c.Auth.ClientSecretFile != "" {
		b, err := os.ReadFile(c.Auth.ClientSecretFile)
		if err != nil {
			return Config{}, fmt.Errorf("clientgeheim: %w", err)
		}
		c.Auth.ClientSecret = strings.TrimSpace(string(b))
	}
	c.resolvePresetPaths(path)
	if err := c.Validate(); err != nil {
		return Config{}, err
	}
	return c, nil
}

func (c *Config) resolvePresetPaths(configFile string) {
	if len(c.CI.Presets) == 0 {
		return
	}
	base := filepath.Dir(configFile)
	for name, p := range c.CI.Presets {
		if p.Dockerfile != "" && !filepath.IsAbs(p.Dockerfile) {
			p.Dockerfile = filepath.Join(base, p.Dockerfile)
			c.CI.Presets[name] = p
		}
	}
}

func (c *Config) applyDefaults() {
	if c.Listen == "" {
		c.Listen = "127.0.0.1:8080"
	}
	if c.StatePath == "" {
		c.StatePath = apppaths.DataDir("/var/lib/bluegit", "BlueGit")
	}
	if c.Auth.Mode == "" {
		c.Auth.Mode = "oauth"
	}
	// base_url hoort bij oauth (auth.timfalken.com). Entra gebruikt issuer/tenant.
	if c.Auth.Mode == "oauth" && c.Auth.BaseURL == "" {
		c.Auth.BaseURL = "https://auth.timfalken.com"
	}
	if c.Auth.RedirectPath == "" {
		c.Auth.RedirectPath = "/auth/callback"
	}
	if c.Auth.UserAgent == "" {
		c.Auth.UserAgent = "BlueGitAccountClient/0.1"
	}
	if c.Auth.DevUser == "" {
		c.Auth.DevUser = "tim"
	}
	if c.Auth.DevAuthID == 0 {
		c.Auth.DevAuthID = 1
	}
	if c.Git.Binary == "" {
		c.Git.Binary = "git"
	}
	if c.Git.DefaultBranch == "" {
		c.Git.DefaultBranch = "master"
	}
	if c.SSH.Listen == "" {
		c.SSH.Listen = "0.0.0.0:2222"
	}
	if c.CI.Docker == "" {
		c.CI.Docker = "docker"
	}
	if c.CI.Concurrency <= 0 {
		c.CI.Concurrency = 1
	}
	if c.CI.Network == "" {
		c.CI.Network = "bridge"
	}
	if c.CI.TimeoutSec <= 0 {
		c.CI.TimeoutSec = 1800
	}
	if strings.TrimSpace(c.Runner.Name) == "" {
		c.Runner.Name = "Steve"
	} else {
		c.Runner.Name = strings.TrimSpace(c.Runner.Name)
	}
	c.Auth.BaseURL = strings.TrimRight(c.Auth.BaseURL, "/")
	c.Auth.Issuer = strings.TrimRight(strings.TrimSpace(c.Auth.Issuer), "/")
	c.Auth.TenantID = strings.TrimSpace(c.Auth.TenantID)
	c.BaseURL = strings.TrimRight(c.BaseURL, "/")
}

// Validate keurt een configuratie goed of af.
func (c *Config) Validate() error {
	if c.BaseURL == "" {
		return fmt.Errorf("base_url ontbreekt")
	}
	u, err := url.Parse(c.BaseURL)
	if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
		return fmt.Errorf("base_url moet een absolute http(s)-URL zijn")
	}
	if strings.TrimSpace(c.StatePath) == "" {
		return fmt.Errorf("state_path ontbreekt")
	}
	if !strings.HasPrefix(c.Auth.RedirectPath, "/") {
		return fmt.Errorf("auth.redirect_path moet met / beginnen")
	}
	switch c.Auth.Mode {
	case "oauth":
		if c.Auth.ClientID == "" || c.Auth.ClientSecret == "" {
			return fmt.Errorf("oauth vereist auth.client_id en een clientgeheim (veld, bestand of BLUEGIT_AUTH_CLIENT_SECRET)")
		}
		if c.Auth.BaseURL == "" {
			return fmt.Errorf("auth.base_url ontbreekt")
		}
	case "entra":
		if c.Auth.TenantID == "" {
			return fmt.Errorf("entra vereist auth.tenant_id")
		}
		if c.Auth.ClientID == "" || c.Auth.ClientSecret == "" {
			return fmt.Errorf("entra vereist auth.client_id en een clientgeheim (veld, bestand of BLUEGIT_AUTH_CLIENT_SECRET)")
		}
		if c.Auth.Issuer != "" {
			if err := validateIssuer(c.Auth.Issuer); err != nil {
				return err
			}
		}
	case "dev":
		if strings.EqualFold(u.Hostname(), "git.timfalken.com") {
			return fmt.Errorf("auth.mode dev is geweigerd voor git.timfalken.com")
		}
	default:
		return fmt.Errorf("auth.mode moet oauth, entra of dev zijn")
	}
	if c.BehindProxy {
		return fmt.Errorf("behind_proxy doet niets meer; zet trusted_proxies op het IP of CIDR van de ingress en haal behind_proxy weg")
	}
	set, err := realip.Parse(c.TrustedProxies)
	if err != nil {
		return err
	}
	c.proxies = set
	if c.SSH.PublicPort < 0 || c.SSH.PublicPort > 65535 {
		return fmt.Errorf("ssh.public_port moet tussen 0 en 65535 liggen")
	}
	if h := strings.TrimSpace(c.SSH.PublicHost); h != "" {
		if strings.Contains(h, "://") || strings.ContainsAny(h, " /") || (strings.Contains(h, ":") && net.ParseIP(h) == nil) {
			return fmt.Errorf("ssh.public_host moet een hostnaam of IP zijn, zonder schema of poort")
		}
	}
	if _, _, err := net.SplitHostPort(c.SSH.Listen); err != nil {
		return fmt.Errorf("ssh.listen moet host:poort zijn")
	}
	if _, err := images.Effective(c.CI.ImageOverrides()); err != nil {
		return err
	}
	if _, _, err := c.Git.MaintenanceEvery(); err != nil {
		return err
	}
	return nil
}

// ProxySet is de geparsede trusted_proxies-lijst. Nil betekent dat
// niemand vertrouwd wordt.
func (c Config) ProxySet() *realip.Set { return c.proxies }

// SSHPublicHost is de host in een SSH-clone-URL.
// Leeg in de config: de host van base_url.
func (c Config) SSHPublicHost() string {
	if h := strings.TrimSpace(c.SSH.PublicHost); h != "" {
		return h
	}
	u, err := url.Parse(c.BaseURL)
	if err != nil {
		return ""
	}
	return u.Hostname()
}

// SSHPublicPort is de poort in een SSH-clone-URL.
// 0 in de config: de poort van ssh.listen.
func (c Config) SSHPublicPort() int {
	if c.SSH.PublicPort > 0 {
		return c.SSH.PublicPort
	}
	_, port, err := net.SplitHostPort(c.SSH.Listen)
	if err != nil {
		return 22
	}
	n, err := strconv.Atoi(port)
	if err != nil || n <= 0 {
		return 22
	}
	return n
}

// CloneSSH is de URL die een gebruiker kloont. Leeg als SSH uit staat.
// Poort 22 geeft git@host:pad.git, een andere poort ssh://git@host:poort/pad.git.
func (c Config) CloneSSH(repoPath string) string {
	if !c.SSH.Enabled {
		return ""
	}
	host := c.SSHPublicHost()
	if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") {
		host = "[" + host + "]"
	}
	if c.SSHPublicPort() == 22 {
		// Korte scp-vorm, zoals GitHub en GitLab. Die kent geen poort.
		return fmt.Sprintf("git@%s:%s.git", host, repoPath)
	}
	return fmt.Sprintf("ssh://git@%s:%d/%s.git", host, c.SSHPublicPort(), repoPath)
}

// RedirectURI is de callback die bij de auth-server geregistreerd moet staan.
func (c Config) RedirectURI() string {
	return c.BaseURL + c.Auth.RedirectPath
}

// validateIssuer eist een absolute URL. HTTP is alleen toegestaan op localhost.
func validateIssuer(issuer string) error {
	iu, err := url.Parse(issuer)
	if err != nil || (iu.Scheme != "https" && iu.Scheme != "http") || iu.Host == "" {
		return fmt.Errorf("auth.issuer moet een absolute http(s)-URL zijn")
	}
	if iu.Scheme != "https" && !issuerLoopback(iu.Hostname()) {
		return fmt.Errorf("auth.issuer moet HTTPS zijn (HTTP alleen op localhost)")
	}
	return nil
}

func issuerLoopback(host string) bool {
	if strings.EqualFold(host, "localhost") {
		return true
	}
	ip := net.ParseIP(host)
	return ip != nil && ip.IsLoopback()
}

// EntraIssuer is de OIDC-issuer voor mode entra.
func (c Config) EntraIssuer() string {
	if c.Auth.Issuer != "" {
		return c.Auth.Issuer
	}
	return "https://login.microsoftonline.com/" + c.Auth.TenantID + "/v2.0"
}

// Example is een startconfiguratie voor de mini-PC.
func Example() string {
	return `# BlueGit op de mini-PC. Kopieer naar /etc/bluegit/config.yml.
# Plain HTTP. TLS en de publieke SSH-poort doet de ingress, zie docs/INGRESS.md.
base_url: https://git.timfalken.com
listen: 0.0.0.0:8080
# Database, sleutel en het gekozen opslagpad. Dit is niet de datadisk.
state_path: /var/lib/bluegit
# storage_path blijft leeg. De installatiebeheerder kiest de datadisk
# bij de eerste aanmelding. Er is geen standaardpad.
# Alleen deze adressen mogen X-Forwarded-For en X-Real-IP zetten.
# Zet hier het IP van de ingress, zoals de mini-PC die verbinding ziet.
trusted_proxies:
  - 10.0.0.2

auth:
  mode: oauth
  base_url: https://auth.timfalken.com
  # Het domein is de client_id. Registreer het pad /auth/callback bij /admin.
  client_id: git.timfalken.com
  # Laat leeg en zet BLUEGIT_AUTH_CLIENT_SECRET, of gebruik client_secret_file.
  client_secret: ""
  client_secret_file: /etc/bluegit/client_secret
  redirect_path: /auth/callback
  user_agent: BlueGitAccountClient/0.1
  # Alternatief: Microsoft Entra ID (OIDC, één tenant). Zet mode op entra
  # en vul tenant_id + client_id; geheim hetzelfde als hierboven.
  # mode: entra
  # tenant_id: 00000000-0000-0000-0000-000000000000
  # client_id: 11111111-1111-1111-1111-111111111111
  # issuer blijft leeg, tenzij je een andere cloud of testissuer nodig hebt.

git:
  binary: git
  default_branch: master
  # Periodiek onderhoud van bare repositories (git maintenance of
  # git gc --auto). Standaard 24h. Zet op off om uit te schakelen.
  # Nooit --prune=now; één repo tegelijk, met gits eigen locking.
  # maintenance_interval: 24h

ssh:
  enabled: true
  # Waar dit proces git-SSH aanneemt. De SSH van het besturingssysteem blijft vrij.
  listen: 0.0.0.0:2222
  # Wat gebruikers in de clone-URL zien. De ingress stuurt poort 22 hiernaartoe.
  public_host: git.timfalken.com
  public_port: 22

runner:
  name: Steve

ci:
  enabled: true
  docker_binary: docker
  concurrency: 1
  network: bridge
  timeout_seconds: 1800
  # Image-aliassen voor jobs. bluegit/base, bluegit/node, bluegit/python,
  # bluegit/go, bluegit/rust, bluegit/java en bluegit/dotnet zijn ingebouwd.
  # Een eigen alias wijst naar een Dockerfile of naar een kant-en-klaar image.
  # presets:
  #   team/tools:
  #     image: alpine:3.20
  #   team/build:
  #     dockerfile: /etc/bluegit/images/build/Dockerfile
  #   bluegit/node:
  #     from: node:22-bookworm
`
}
