package main

import (
	"git.yeij.top/AskaEth/Cyrene/pkg/logger"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"git.yeij.top/AskaEth/Cyrene/memory-service/internal/config"
	"git.yeij.top/AskaEth/Cyrene/memory-service/internal/handler"
	"git.yeij.top/AskaEth/Cyrene/memory-service/internal/service"
	"git.yeij.top/AskaEth/Cyrene/memory-service/internal/store"
)

func main() {
	logger.SetDefault(logger.New("memory-service"))
	logger.Println("🧠 Memory-Service 启动中...")

	// 加载配置
	cfg := config.Load()

	logger.Printf("配置: 端口=%s, 数据库=%s...", cfg.Port, maskDBURL(cfg.DatabaseURL))

	// 初始化数据库存储
	memStore := store.NewStore(cfg.DatabaseURL)
	defer memStore.Close()

	// 初始化服务层
	svc := service.NewMemoryService(memStore)

	// 初始化 HTTP 处理器
	h := handler.NewMemoryHandler(svc)

	// 注册路由
	mux := http.NewServeMux()
	h.RegisterRoutes(mux)

	// 健康检查端点
	mux.HandleFunc("/api/v1/health", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		status := "ok"
		if !memStore.IsReady() {
			status = "degraded"
		}
		w.Write([]byte(`{"status":"` + status + `","service":"memory-service"}`))
	})

	// 启动 HTTP 服务
	srv := &http.Server{
		Addr:    ":" + cfg.Port,
		Handler: mux,
	}

	go func() {
		logger.Printf("🚀 Memory-Service 已启动在端口 %s", cfg.Port)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Fatalf("服务启动失败: %v", err)
		}
	}()

	// 优雅关闭
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	logger.Println("正在关闭 Memory-Service...")
	srv.Close()
	logger.Println("Memory-Service 已关闭")
}

func maskDBURL(url string) string {
	if len(url) > 30 {
		return url[:30] + "..."
	}
	return url
}
