package config

import (
	"log"
	"strings"

	"github.com/spf13/viper"
)

type Config struct {
	GCPProjectID string `mapstructure:"gcp_project_id"`
	Telegram     struct {
		Token   string  `mapstructure:"token"`
		ChatIDs []int64 `mapstructure:"chat_ids"`
	} `mapstructure:"telegram"`
}

func Load() (Config, error) {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".")

	viper.SetEnvPrefix("CRAWLER")
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	viper.AutomaticEnv()

	var cfg Config
	if err := viper.ReadInConfig(); err != nil {
		// If the error is that the file wasn't found, that's okay. Log it and continue.
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			log.Println("ℹ️ No 'config.yaml' file found. Relying on environment variables or flags.")
		} else {
			// For any other error (e.g., malformed YAML), return the error.
			return cfg, err
		}
	}

	if err := viper.Unmarshal(&cfg); err != nil {
		return cfg, err
	}
	return cfg, nil
}
