package lib

import (
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/joho/godotenv"
)

func getConfig() Config {
	intervalMinutes, err := strconv.Atoi(os.Getenv("INTERVAL_MINUTES"))
	if err != nil {
		intervalMinutes = 5
	}

	return Config{
		WikiBaseURL:    os.Getenv("WIKI_BASE_URL"),
		WikiToken:      os.Getenv("WIKI_TOKEN"),
		RedmineBaseURL: os.Getenv("REDMINE_BASE_URL"),
		RedmineKey:     os.Getenv("REDMINE_KEY"),
		GiteaToken:     os.Getenv("GITEA_TOKEN"),
		GiteaBaseURL:   os.Getenv("GITEA_BASE_URL"),
		GiteaRepos:     strings.Split(os.Getenv("GITEA_REPOS"), ","),
		DiscordWebhook: os.Getenv("DISCORD_WEBHOOK"),
		DiscordFake:    os.Getenv("DISCORD_FAKE") == "true",
		Interval:       time.Duration(intervalMinutes) * time.Minute,
	}
}

func getFetchers(config *Config, cache *Cache) []Fetcher {
	var fetchers []Fetcher

	fetchers = append(fetchers, &GiteaFetcher{
		BaseURL: config.GiteaBaseURL,
		Token:   config.GiteaToken,
		Repos:   config.GiteaRepos,
		Cache:   cache,
	})

	fetchers = append(fetchers, &WikiFetcher{
		BaseURL: config.WikiBaseURL,
		Token:   config.WikiToken,
		Cache:   cache,
	})
	fetchers = append(fetchers, &RedmineFetcher{
		BaseURL: config.RedmineBaseURL,
		Key:     config.RedmineKey,
		Cache:   cache,
	})

	return fetchers
}

func getCache() Cache {
	cache := *NewCache()
	cache.Load()
	return cache
}

func getDiscordSender(config Config) DiscordSender {
	return DiscordSender{
		Webhook: config.DiscordWebhook,
		Fake:    config.DiscordFake,
	}
}

func getMessages(fetchers []Fetcher) []string {
	messages := []string{}
	for _, fetcher := range fetchers {
		entries := fetcher.Fetch()
		for _, entry := range entries {
			messages = append(messages, fmt.Sprintf("[%s](%s)", entry.Title, entry.URL))
		}
	}
	return messages
}

func loadEnv() {
	if err := godotenv.Load(); err != nil {
		log.Println("Warning: .env file not found, using environment variables")
	}
}

func Runner() {
	loadEnv()
	config := getConfig()
	cache := getCache()
	discord_sender := getDiscordSender(config)
	fetchers := getFetchers(&config, &cache)
	for {
		log.Println("Run updater...")
		messages := getMessages(fetchers)
		discord_sender.SendBatch(messages)
		cache.Save()
		time.Sleep(config.Interval)
	}
}
