package main

import (
	"log/slog"
	"os"
	"time"

	"github.com/gin-gonic/gin"

	"dudu/server/internal/auth"
	"dudu/server/internal/config"
	"dudu/server/internal/httpapi"
	"dudu/server/internal/quota"
	"dudu/server/internal/store"
)

func main() {
	slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil)))
	cfg := config.Load()

	db, err := store.Open(cfg.PostgresDSN)
	if err != nil {
		slog.Error("postgres open failed", "err", err)
		os.Exit(1)
	}
	rdb := store.OpenRedis(cfg.RedisAddr, cfg.RedisDB)

	jwt := auth.NewJWT(cfg.JWTSecret, time.Duration(cfg.JWTTTLHours)*time.Hour, rdb)
	qm := quota.New(rdb, db)

	gin.SetMode(gin.ReleaseMode)
	r := gin.New()
	r.Use(gin.Recovery())

	httpapi.Register(r, &httpapi.Deps{Cfg: cfg, DB: db, RDB: rdb, JWT: jwt, Quota: qm})

	slog.Info("dudu server listening", "addr", cfg.Addr, "asr_provider", cfg.ASRProvider)
	if err := r.Run(cfg.Addr); err != nil {
		slog.Error("server exited", "err", err)
		os.Exit(1)
	}
}
