// security-center api service entrypoint.
//
// @title			Security Center Agent API
// @version		1.0
// @description	Read-only APIs for the Security Center CAASM (asset) and Vuln (vulnerability) modules. Both success and business errors return HTTP 200, distinguished via the APIResponse envelope (code/message/data/timestamp).
//
// @securityDefinitions.apikey	agentApiKey
// @in							header
// @name						X-API-Key
// @description				Agent M2M authentication (X-API-Key).
//
// @securityDefinitions.apikey	bearerAuth
// @in							header
// @name						Authorization
// @description				Human user JWT (Authorization: Bearer <access_token>).
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"log/slog"
	"os"
	"os/signal"
	"syscall"
	"time"

	"security-center-backend/internal/config"
	"security-center-backend/internal/pkg/logger"
	"security-center-backend/internal/server"
)

func main() {
	var configPath string
	flag.StringVar(&configPath, "config", "./configs/config.yaml", "path to the configuration file")
	flag.Parse()

	cfg, err := config.Load(configPath)
	if err != nil {
		log.Fatalf("failed to load config: %v", err)
	}

	appLogger := logger.New(cfg.Log)
	defer func() { _ = appLogger.Sync() }()
	// 中间件/业务层大量使用包级 slog（slog.Warn/Debug 等，如 agent 求交、写防护、防冒充日志），
	// 不走注入的 appLogger。不同步默认 logger 时这些日志不受 log.level 控制（Debug 求交日志丢失），
	// 排障无法按层级关键词定位（tests/e2e/vuln_write_e2e.md §0.2）。
	slog.SetDefault(appLogger.Logger)

	appLogger.Info("starting security center api service",
		"env", cfg.App.Environment,
		"port", cfg.HTTP.Port,
		"bypass_sso", cfg.Auth.BypassSSO,
	)

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	app, cleanup, err := server.NewApplication(cfg, appLogger)
	if err != nil {
		appLogger.Error("failed to initialize application", "error", err)
		os.Exit(1)
	}
	defer cleanup()

	go func() {
		if err := app.Run(); err != nil {
			appLogger.Error("server stopped with error", "error", err)
			stop()
		}
	}()

	<-ctx.Done()
	appLogger.Info("shutdown signal received, shutting down gracefully")

	shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	if err := app.Stop(shutdownCtx); err != nil {
		appLogger.Error("graceful shutdown failed", "error", err)
		fmt.Fprintf(os.Stderr, "graceful shutdown failed: %v\n", err)
		os.Exit(1)
	}

	appLogger.Info("security center api service stopped")
}
