package config

import (
	"fmt"
	"os"
	"strconv"
	"strings"

	"gopkg.in/yaml.v3"
)

type Config struct {
	Server         ServerConfig         `yaml:"server"`
	Database       DatabaseConfig       `yaml:"database"`
	Log            LogConfig            `yaml:"log"`
	Auth           AuthConfig           `yaml:"auth"`
	Library        LibraryConfig        `yaml:"library"`
	Subsonic       SubsonicConfig       `yaml:"subsonic"`
	Events         EventsConfig         `yaml:"events"`
	Recommendation RecommendationConfig `yaml:"recommendation"`
}

type ServerConfig struct {
	Address string `yaml:"address"`
}

type DatabaseConfig struct {
	URL string `yaml:"url"`
}

type LogConfig struct {
	Level  string `yaml:"level"`
	Format string `yaml:"format"`
}

type AuthConfig struct {
	AdminBootstrap AdminBootstrapConfig `yaml:"admin_bootstrap"`
}

// AdminBootstrapConfig drives the one-shot admin creation on an empty users
// table. Username is required to enable the flow; leaving Password blank asks
// the server to generate a random one and log it to stderr.
type AdminBootstrapConfig struct {
	Username string `yaml:"username"`
	Password string `yaml:"password"`
}

type LibraryConfig struct {
	ScanPaths     []string `yaml:"scan_paths"`
	ScanOnStartup bool     `yaml:"scan_on_startup"`
}

// SubsonicConfig controls wire-format concessions on the /rest/* surface.
// AllowPlaintextPassword gates the `p=` parameter; the recommended posture is
// to leave it disabled and require apiKey (OpenSubsonic) or t+s.
type SubsonicConfig struct {
	AllowPlaintextPassword bool `yaml:"allow_plaintext_password"`
}

// EventsConfig governs play-event ingestion: session window, skip rule.
type EventsConfig struct {
	SessionTimeoutMinutes   int     `yaml:"session_timeout_minutes"`
	SkipMaxCompletionRatio  float64 `yaml:"skip_max_completion_ratio"`
	SkipMaxDurationPlayedMs int     `yaml:"skip_max_duration_played_ms"`
}

// RecommendationConfig governs the M3 weighted-shuffle scoring (spec §6).
// All weights are operator-tunable; defaults match the spec recommendations.
type RecommendationConfig struct {
	BaseWeight          float64 `yaml:"base_weight"`
	LikeBoost           float64 `yaml:"like_boost"`
	RecencyWeight       float64 `yaml:"recency_weight"`
	SkipPenalty         float64 `yaml:"skip_penalty"`
	JitterMagnitude     float64 `yaml:"jitter_magnitude"`
	ContextWeight       float64 `yaml:"context_weight"`
	RecentlyPlayedHours int     `yaml:"recently_played_hours"`
	RadioSize           int     `yaml:"radio_size"`
	RadioSizeMax        int     `yaml:"radio_size_max"`
}

func Default() Config {
	return Config{
		Server:   ServerConfig{Address: ":4533"},
		Database: DatabaseConfig{URL: ""},
		Log:      LogConfig{Level: "info", Format: "text"},
		Events: EventsConfig{
			SessionTimeoutMinutes:   30,
			SkipMaxCompletionRatio:  0.5,
			SkipMaxDurationPlayedMs: 30000,
		},
		Recommendation: RecommendationConfig{
			BaseWeight:          1.0,
			LikeBoost:           2.0,
			RecencyWeight:       1.0,
			SkipPenalty:         1.0,
			JitterMagnitude:     0.1,
			ContextWeight:       2.0,
			RecentlyPlayedHours: 1,
			RadioSize:           50,
			RadioSizeMax:        200,
		},
	}
}

func Load(path string) (Config, error) {
	cfg := Default()
	if path != "" {
		data, err := os.ReadFile(path)
		if err != nil {
			if !os.IsNotExist(err) {
				return cfg, fmt.Errorf("read config %q: %w", path, err)
			}
		} else if err := yaml.Unmarshal(data, &cfg); err != nil {
			return cfg, fmt.Errorf("parse config %q: %w", path, err)
		}
	}
	applyEnv(&cfg)
	return cfg, nil
}

func applyEnv(cfg *Config) {
	if v, ok := os.LookupEnv("SMARTMUSIC_SERVER_ADDRESS"); ok {
		cfg.Server.Address = v
	}
	if v, ok := os.LookupEnv("SMARTMUSIC_DATABASE_URL"); ok {
		cfg.Database.URL = v
	}
	if v, ok := os.LookupEnv("SMARTMUSIC_LOG_LEVEL"); ok {
		cfg.Log.Level = strings.ToLower(v)
	}
	if v, ok := os.LookupEnv("SMARTMUSIC_LOG_FORMAT"); ok {
		cfg.Log.Format = strings.ToLower(v)
	}
	if v, ok := os.LookupEnv("SMARTMUSIC_AUTH_ADMIN_USERNAME"); ok {
		cfg.Auth.AdminBootstrap.Username = v
	}
	if v, ok := os.LookupEnv("SMARTMUSIC_AUTH_ADMIN_PASSWORD"); ok {
		cfg.Auth.AdminBootstrap.Password = v
	}
	if v, ok := os.LookupEnv("SMARTMUSIC_LIBRARY_SCAN_PATHS"); ok {
		cfg.Library.ScanPaths = splitPaths(v)
	}
	if v, ok := os.LookupEnv("SMARTMUSIC_LIBRARY_SCAN_ON_STARTUP"); ok {
		if b, err := strconv.ParseBool(v); err == nil {
			cfg.Library.ScanOnStartup = b
		}
	}
	if v, ok := os.LookupEnv("SMARTMUSIC_SUBSONIC_ALLOW_PLAINTEXT_PASSWORD"); ok {
		if b, err := strconv.ParseBool(v); err == nil {
			cfg.Subsonic.AllowPlaintextPassword = b
		}
	}
}

// splitPaths splits a colon-separated path list, dropping empty entries.
// Colon matches PATH-style Unix conventions; Minstrel ships Linux-only.
func splitPaths(s string) []string {
	parts := strings.Split(s, ":")
	out := parts[:0]
	for _, p := range parts {
		if p != "" {
			out = append(out, p)
		}
	}
	return out
}
