package config

import (
	"bufio"
	"os"
	"strconv"
	"strings"
)

type Config struct {
	OSC OSCConfig
}

type OSCConfig struct {
	Host string
	Port int
}

func Load(path string) (*Config, error) {
	cfg := &Config{OSC: OSCConfig{Host: "127.0.0.1", Port: 9001}}
	file, err := os.Open(path)
	if err != nil {
		return cfg, nil
	}
	defer file.Close()

	var section string
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
			section = strings.Trim(line, "[]")
			continue
		}
		parts := strings.SplitN(line, "=", 2)
		if len(parts) != 2 {
			continue
		}
		key := strings.TrimSpace(parts[0])
		val := strings.TrimSpace(parts[1])
		val = strings.Trim(val, "\"'")
		if section == "osc" {
			switch key {
			case "host":
				cfg.OSC.Host = val
			case "port":
				if n, err := strconv.Atoi(val); err == nil {
					cfg.OSC.Port = n
				}
			}
		}
	}
	return cfg, scanner.Err()
}

