// Package config loads application configuration from a YAML file and
// overlays it with environment variables. Environment variables always win,
// so the same image can be reconfigured without editing config.yaml.
package config

import (
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"gopkg.in/yaml.v3"
)

// Config is the full runtime configuration of the application.
type Config struct {
	Bot      BotConfig      `yaml:"bot"`
	Web      WebConfig      `yaml:"web"`
	Database DatabaseConfig `yaml:"database"`
	Limits   LimitsConfig   `yaml:"limits"`
	Proxy    ProxyConfig    `yaml:"proxy"`
	Logging  LoggingConfig  `yaml:"logging"`
}

type BotConfig struct {
	Token            string   `yaml:"token"`
	Admins           []int64  `yaml:"admins"`
	DefaultLanguage  string   `yaml:"default_language"`
	WhitelistEnabled bool     `yaml:"whitelist_enabled"`
	Whitelist        []int64  `yaml:"whitelist"`
}

type WebConfig struct {
	Addr           string `yaml:"addr"`
	BaseURL        string `yaml:"base_url"`
	AdminUser      string `yaml:"admin_user"`
	AdminPassword  string `yaml:"admin_password"`
	JWTSecret      string `yaml:"jwt_secret"`
	RealIPHeader   string `yaml:"real_ip_header"`
}

type DatabaseConfig struct {
	Path string `yaml:"path"`
}

type LimitsConfig struct {
	Daily            int `yaml:"daily"`
	CooldownSeconds  int `yaml:"cooldown_seconds"`
}

type ProxyConfig struct {
	Mode            string `yaml:"mode"`
	TimeoutSeconds  int    `yaml:"timeout_seconds"`
}

type LoggingConfig struct {
	Level string `yaml:"level"`
	File  string `yaml:"file"`
}

// Default returns a config with sensible defaults so the app can boot even
// when no file is present (everything important is then filled from env).
func Default() *Config {
	return &Config{
		Bot: BotConfig{
			Token:           "",
			Admins:          nil,
			DefaultLanguage: "fa",
		},
		Web: WebConfig{
			Addr:          ":8080",
			BaseURL:       "http://localhost:8080",
			AdminUser:     "admin",
			AdminPassword: "changeme",
			JWTSecret:     "please-change-this",
		},
		Database: DatabaseConfig{Path: "./data/bot.db"},
		Limits:   LimitsConfig{Daily: 3, CooldownSeconds: 60},
		Proxy:    ProxyConfig{Mode: "round_robin", TimeoutSeconds: 20},
		Logging:  LoggingConfig{Level: "info", File: "./data/bot.log"},
	}
}

// Load reads the YAML file at path (if it exists) and then applies
// environment-variable overrides. Missing file is not an error: the defaults
// plus env vars are enough to run.
func Load(path string) (*Config, error) {
	cfg := Default()

	if path != "" {
		if data, err := os.ReadFile(path); err != nil {
			if !os.IsNotExist(err) {
				return nil, fmt.Errorf("read config %s: %w", path, err)
			}
			// missing file is fine
		} else if err := yaml.Unmarshal(data, cfg); err != nil {
			return nil, fmt.Errorf("parse config %s: %w", path, err)
		}
	}

	applyEnv(cfg)

	if err := cfg.validate(); err != nil {
		return nil, err
	}
	cfg.absPaths()
	return cfg, nil
}

// applyEnv overlays well-known environment variables on top of the loaded
// config. This keeps deployments (Docker, systemd) simple.
func applyEnv(cfg *Config) {
	if v := os.Getenv("BOT_TOKEN"); v != "" {
		cfg.Bot.Token = v
	}
	if v := os.Getenv("ADMIN_IDS"); v != "" {
		cfg.Bot.Admins = parseIntList(v)
	}
	if v := os.Getenv("WEB_URL"); v != "" {
		cfg.Web.BaseURL = v
	}
	if v := os.Getenv("WEB_ADDR"); v != "" {
		cfg.Web.Addr = v
	}
	if v := os.Getenv("WEB_ADMIN_USER"); v != "" {
		cfg.Web.AdminUser = v
	}
	if v := os.Getenv("WEB_ADMIN_PASSWORD"); v != "" {
		cfg.Web.AdminPassword = v
	}
	if v := os.Getenv("WEB_JWT_SECRET"); v != "" {
		cfg.Web.JWTSecret = v
	}
	if v := os.Getenv("DB_PATH"); v != "" {
		cfg.Database.Path = v
	}
	if v := os.Getenv("DAILY_LIMIT"); v != "" {
		if n, err := strconv.Atoi(v); err == nil {
			cfg.Limits.Daily = n
		}
	}
}

func parseIntList(s string) []int64 {
	out := make([]int64, 0)
	for _, part := range strings.Split(s, ",") {
		part = strings.TrimSpace(part)
		if part == "" {
			continue
		}
		n, err := strconv.ParseInt(part, 10, 64)
		if err == nil {
			out = append(out, n)
		}
	}
	return out
}

func (c *Config) validate() error {
	if c.Bot.Token == "" || !strings.Contains(c.Bot.Token, ":") {
		return fmt.Errorf("bot.token is required (get it from @BotFather)")
	}
	if len(c.Bot.Admins) == 0 {
		return fmt.Errorf("bot.admins must list at least one Telegram user id")
	}
	if c.Web.JWTSecret == "" || len(c.Web.JWTSecret) < 16 {
		return fmt.Errorf("web.jwt_secret must be at least 16 characters")
	}
	if c.Web.AdminPassword == "" {
		return fmt.Errorf("web.admin_password is required")
	}
	if c.Limits.Daily < 0 {
		return fmt.Errorf("limits.daily must be >= 0")
	}
	if c.Database.Path == "" {
		return fmt.Errorf("database.path is required")
	}
	return nil
}

// absPaths turns the database and log file paths into absolute paths so the
// working directory does not matter at runtime.
func (c *Config) absPaths() {
	if !filepath.IsAbs(c.Database.Path) {
		if abs, err := filepath.Abs(c.Database.Path); err == nil {
			c.Database.Path = abs
		}
	}
	if c.Logging.File != "" && !filepath.IsAbs(c.Logging.File) {
		if abs, err := filepath.Abs(c.Logging.File); err == nil {
			c.Logging.File = abs
		}
	}
}

// IsAdmin reports whether uid is in the configured admin list.
func (c *Config) IsAdmin(uid int64) bool {
	for _, a := range c.Bot.Admins {
		if a == uid {
			return true
		}
	}
	return false
}
