package main

import (
	"log"

	"senlinai-agent/backend/internal/config"
	"senlinai-agent/backend/internal/httpx"
	"senlinai-agent/backend/internal/logic/ai"
	"senlinai-agent/backend/internal/logic/auth"
	"senlinai-agent/backend/internal/logic/files"
	"senlinai-agent/backend/internal/logic/inbox"
	"senlinai-agent/backend/internal/logic/projects"
	"senlinai-agent/backend/internal/logic/search"
	"senlinai-agent/backend/internal/logic/tasks"
	"senlinai-agent/backend/internal/models"
)

func main() {
	cfg := config.Load()

	err := models.New(cfg.DSN)
	if err != nil {
		log.Fatal(err)
	}

	authService := auth.NewService(cfg.AuthSecret)
	projectService := projects.NewService()
	fileService := files.NewService(cfg.StorageDir, models.DBService)
	taskService := tasks.NewService(models.DBService)
	projectHandler := projects.NewHandler(projectService)
	tagHandler := projects.NewTagHandler(projectService)
	cronHandler := projects.NewCronHandler(projectService)
	taskHandler := tasks.NewHandler(taskService)
	fileHandler := files.NewHandler(fileService, cfg.MaxUploadBytes)
	inboxHandler := inbox.NewHandler(inbox.NewService(inbox.StaticAnalyzer{}))
	searchHandler := search.NewHandler(search.NewService(models.DBService))
	aiGateway := ai.NewGatewayWithSecret(cfg.SystemAIKey, cfg.AIKeyEncryptionSecret)
	aiHandler := ai.NewHandler(ai.NewSessionService(aiGateway))
	authHandler := auth.NewHandler(authService)
	appRouter := httpx.NewProtectedRouter(
		cfg,
		authService.VerifySession,
		authHandler,
		projectHandler,
		tagHandler,
		cronHandler,
		taskHandler,
		fileHandler,
		inboxHandler,
		searchHandler,
		aiHandler,
	)
	if err := appRouter.Run(":" + cfg.Port); err != nil {
		log.Fatal(err)
	}
}
