package config

import (
	"fmt"
	"log"
	"os"
	legacy "weatherstation/internal/config"
)

type Config struct {
	Addr          string
	UIServeDir    string
	BigscreenDir  string
	TemplateDir   string
	StaticDir     string
	DevEnableCORS bool
	Legacy        *legacy.Config
}

func Load() Config {
	lg := legacy.GetConfig()

	port := lg.Server.WebPort
	if port <= 0 {
		port = 8080
	}

	cfg := Config{
		Addr:          fmt.Sprintf(":%d", port),
		UIServeDir:    "core/frontend/dist/ui",
		BigscreenDir:  "core/frontend/dist/bigscreen",
		TemplateDir:   "templates",
		StaticDir:     "static",
		DevEnableCORS: true,
		Legacy:        lg,
	}

	if v := os.Getenv("CORE_ADDR"); v != "" {
		cfg.Addr = v
	}
	if v := os.Getenv("CORE_UI_DIR"); v != "" {
		cfg.UIServeDir = v
	}
	if v := os.Getenv("CORE_BIGSCREEN_DIR"); v != "" {
		cfg.BigscreenDir = v
	}
	if v := os.Getenv("CORE_TEMPLATE_DIR"); v != "" {
		cfg.TemplateDir = v
	}
	if v := os.Getenv("CORE_STATIC_DIR"); v != "" {
		cfg.StaticDir = v
	}
	if v := os.Getenv("CORE_ENABLE_CORS"); v != "" {
		if v == "0" || v == "false" {
			cfg.DevEnableCORS = false
		} else {
			cfg.DevEnableCORS = true
		}
	}

	log.Printf("config: addr=%s ui=%s bigscreen=%s tpl=%s static=%s cors=%v", cfg.Addr, cfg.UIServeDir, cfg.BigscreenDir, cfg.TemplateDir, cfg.StaticDir, cfg.DevEnableCORS)
	return cfg
}
