package main

import (
	"flag"
	"os"

	"github.com/joho/godotenv"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"

	"pluja.dev/kycnot.me/config"
	"pluja.dev/kycnot.me/database"
	"pluja.dev/kycnot.me/server"
	"pluja.dev/kycnot.me/utils/maintenance"
	"pluja.dev/kycnot.me/utils/tos_scraper"
)

var (
	// Flags
	dev     = flag.Bool("dev", false, "sets dev mode")
	nocache = flag.Bool("nocache", false, "disables cache")
	scraper = flag.Bool("scrap", false, "enables the scraper")
	listen  = flag.String("listen", ":4488", "address to listen to")
)

func init() {
	// Flags
	flag.Parse()
	config.Conf = config.Config{
		Dev:        *dev,
		Cache:      *nocache,
		Scraper:    *scraper,
		ListenAddr: *listen,
	}

	// Flags
	log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout}).With().Logger()
	zerolog.SetGlobalLevel(zerolog.InfoLevel)

	if *dev {
		log.Logger = log.Output(
			zerolog.ConsoleWriter{
				Out:        os.Stdout,
				TimeFormat: "02.01.2006 15:04:05",
			},
		).With().Caller().Logger()
		zerolog.SetGlobalLevel(zerolog.DebugLevel)
		log.Debug().Msg("DEV mode enabled")
	}

	if *nocache {
		log.Debug().Msg("Cache disabled")
	}

	// Load .env file
	log.Info().Msg("Loading .env file.")
	err := godotenv.Load()
	if err != nil {
		log.Info().Msg("No .env file found, using environment variables")
	}

	// Load donation addresses into config
	config.Conf.Donations.Xmr = os.Getenv("XMR_ADDRESS")
	config.Conf.Donations.Btc = os.Getenv("BTC_ADDRESS")
	config.Conf.Donations.Lnn = os.Getenv("LNN_ADDRESS")

	// Database init
	log.Info().Msg("Initializing database.")
	database.InitPocketbase()

	// AI ToS Scraper init
	if config.Conf.Scraper {
		log.Info().Msg("Initializing AI ToS scraper.")
		tos_scraper.InitTosScraperDaemon()
	}

	// Maintenance init
	log.Info().Msg("Initializing maintenance daemon.")
	maintenance.InitMaintenanceDaemon()
}

func main() {
	// Server init
	log.Info().Msg("Initializing server.")
	server := server.NewServer(config.Conf.ListenAddr)

	if err := server.Run(); err != nil {
		log.Fatal().Err(err)
	}
}
