package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

type Config struct {
	AppID          string
	AppSecret      string
	RefreshMinutes int
	TTLMinutes     int
	Channels       []string
	CDNDomains     []string
	Port           int
	DataDir        string
	ServeFeeds     bool
}

var defaultConfigDirs = []string{
	"/etc/tweed",
	"/usr/local/etc/tweed",
}

var defaultDataDirs = []string{
	"/var/db/tweed",
	"/var/lib/tweed",
}

func findConfigDir(given string) (string, error) {
	if given != "" {
		return given, nil
	}
	for _, d := range defaultConfigDirs {
		if _, err := os.Stat(filepath.Join(d, "config.ini")); !errors.Is(err, os.ErrNotExist) {
			return d, nil
		}
	}
	return "", fmt.Errorf("no config.ini found (looked in %s)",
		strings.Join(defaultConfigDirs, ", "))
}

func findDataDir() (string, error) {
	for _, d := range defaultDataDirs {
		fi, err := os.Stat(d)
		if errors.Is(err, fs.ErrNotExist) {
			continue
		}
		if err != nil {
			return "", fmt.Errorf("data dir %s: %w", d, err)
		}
		if !fi.IsDir() {
			return "", fmt.Errorf("data dir %s: not a directory", d)
		}
		return d, nil
	}
	return "", fmt.Errorf("no data directory found (looked for %s)",
		strings.Join(defaultDataDirs, ", "))
}

func defaultCDNDomains() []string {
	return []string{
		"vod-secure.twitch.tv",
		"vod-metro.twitch.tv",
		"vod-pop-secure.twitch.tv",
		"d2vi6trrdongqn.cloudfront.net",
		"d2e2de1etea730.cloudfront.net",
		"dqrpb9wgowsf5.cloudfront.net",
		"ds0h3roq6wcgc.cloudfront.net",
		"d2nvs31859zcd8.cloudfront.net",
		"d2aba1wr3818hz.cloudfront.net",
		"d3c27h4odz752x.cloudfront.net",
		"dgeft87wbj63p.cloudfront.net",
		"d1m7jfoe9zdc1j.cloudfront.net",
		"d1ymi26ma8va5x.cloudfront.net",
		"d2vjef5jvl6bfs.cloudfront.net",
		"d3vd9lfkzbru3h.cloudfront.net",
		"d1mhjrowxxagfy.cloudfront.net",
		"ddacn6pr5v0tl.cloudfront.net",
		"d3aqoihi2n8ty8.cloudfront.net",
		"d1xhnb4ptk05mw.cloudfront.net",
		"d6tizftlrpuof.cloudfront.net",
		"d36nr0u3xmc4mm.cloudfront.net",
		"d1oca24q5dwo6d.cloudfront.net",
		"d2um2qdswy1tb0.cloudfront.net",
		"d1w2poirtb3as9.cloudfront.net",
		"d6d4ismr40iw.cloudfront.net",
		"d1g1f25tn8m2e6.cloudfront.net",
		"dykkng5hnh52u.cloudfront.net",
		"d2dylwb3shzel1.cloudfront.net",
		"d2xmjdvx03ij56.cloudfront.net",
		"d3fi1amfgojobc.cloudfront.net",
	}
}

func loadCDNDomains(dir string) []string {
	p := filepath.Join(dir, "cdns")
	data, err := os.ReadFile(p)
	if err != nil {
		if !errors.Is(err, os.ErrNotExist) {
			logWarn("read cdns file %s: %v", p, err)
		}
		return defaultCDNDomains()
	}

	var candidates []string
	for l := range strings.SplitSeq(string(data), "\n") {
		l = strings.TrimSpace(l)
		if l == "" || strings.HasPrefix(l, "#") {
			continue
		}
		candidates = append(candidates, l)
	}
	if len(candidates) == 0 {
		return defaultCDNDomains()
	}
	return candidates
}

func parsePositiveInt(val string) (int, error) {
	n, err := strconv.Atoi(val)
	if err != nil || n < 1 {
		return 0, fmt.Errorf("%q is not a positive integer", val)
	}
	return n, nil
}

func loadConfig(dir string) (Config, error) {
	b, err := os.ReadFile(filepath.Join(dir, "config.ini"))
	if err != nil {
		return Config{}, fmt.Errorf("reading config: %w", err)
	}
	lines := strings.Split(string(b), "\n")
	cfg := Config{ServeFeeds: true}

	for lineNum, raw := range lines {
		line := strings.TrimSpace(raw)
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		parts := strings.SplitN(line, "=", 2)
		if len(parts) != 2 {
			return Config{}, fmt.Errorf("line %d: illegal formatting, expected key = value", lineNum)
		}
		key := strings.TrimSpace(parts[0])
		val := strings.TrimSpace(parts[1])
		switch key {
		case "appId":
			cfg.AppID = val
		case "appSecret":
			cfg.AppSecret = val
		case "refreshMinutes":
			n, err := parsePositiveInt(val)
			if err != nil {
				return Config{}, fmt.Errorf("line %d: illegal refreshMinutes: %w", lineNum, err)
			}
			cfg.RefreshMinutes = n
		case "ttlMinutes":
			n, err := parsePositiveInt(val)
			if err != nil {
				return Config{}, fmt.Errorf("line %d: illegal ttlMinutes: %w", lineNum, err)
			}
			cfg.TTLMinutes = n
		case "channels":
			parts := strings.Split(val, ",")
			for _, p := range parts {
				p = strings.TrimSpace(p)
				if p != "" {
					cfg.Channels = append(cfg.Channels, p)
				}
			}
		case "port":
			n, err := parsePositiveInt(val)
			if err != nil || n > 65535 {
				return Config{}, fmt.Errorf("line %d: illegal port: %q must be 1-65535", lineNum, val)
			}
			cfg.Port = n
		case "dataDir":
			if val == "" {
				return Config{}, fmt.Errorf("line %d: empty dataDir value", lineNum)
			}
			if !filepath.IsAbs(val) {
				return Config{}, fmt.Errorf("line %d: illegal dataDir: path must be absolute", lineNum)
			}
			cfg.DataDir = val
		case "serveFeeds":
			b, err := strconv.ParseBool(val)
			if err != nil {
				return Config{}, fmt.Errorf("line %d: illegal serveFeeds: %q is not a boolean", lineNum, val)
			}
			cfg.ServeFeeds = b
		default:
			return Config{}, fmt.Errorf("line %d: illegal key %q", lineNum, key)
		}
	}

	if cfg.AppID == "" || cfg.AppSecret == "" {
		return cfg, errors.New("missing required appId and/or appSecret in config")
	}
	if cfg.RefreshMinutes == 0 {
		cfg.RefreshMinutes = 5
	}
	if cfg.TTLMinutes == 0 {
		cfg.TTLMinutes = 30
	}
	if cfg.Port == 0 {
		cfg.Port = 8081
	}
	if cfg.DataDir == "" {
		cfg.DataDir, err = findDataDir()
		if err != nil {
			return Config{}, err
		}
	}
	if len(cfg.Channels) == 0 {
		return Config{}, errors.New("found no channels, no point in running")
	}

	cfg.CDNDomains = loadCDNDomains(dir)

	return cfg, nil
}
