// Filename: internal/container/container.go
package container

import (
	"fmt"
	"gemini-balancer/internal/app"
	"gemini-balancer/internal/channel"
	"gemini-balancer/internal/config"
	"gemini-balancer/internal/crypto"
	"gemini-balancer/internal/db"
	"gemini-balancer/internal/db/dialect"
	"gemini-balancer/internal/db/migrations"
	"gemini-balancer/internal/domain/proxy"
	"gemini-balancer/internal/domain/upstream"
	"gemini-balancer/internal/handlers"
	"gemini-balancer/internal/logging"
	"gemini-balancer/internal/models"
	"gemini-balancer/internal/repository"
	"gemini-balancer/internal/router"
	"gemini-balancer/internal/scheduler"
	"gemini-balancer/internal/service"
	"gemini-balancer/internal/settings"
	"gemini-balancer/internal/store"
	"gemini-balancer/internal/syncer"
	"gemini-balancer/internal/task"
	"gemini-balancer/internal/webhandlers"

	"github.com/sirupsen/logrus"
	"go.uber.org/dig"
	"gorm.io/gorm"
)

func BuildContainer() (*dig.Container, error) {
	container := dig.New()

	// =========== 阶段一: 基础设施层 (Infrastructure) ===========
	container.Provide(config.LoadConfig)

	container.Provide(func(cfg *config.Config, logger *logrus.Logger) (*gorm.DB, dialect.DialectAdapter, error) {
		gormDB, adapter, err := db.NewDB(cfg, logger)
		if err != nil {
			return nil, nil, err
		}
		// 迁移运行逻辑
		if err := migrations.RunVersionedMigrations(gormDB, cfg, logger); err != nil {
			return nil, nil, fmt.Errorf("failed to run versioned migrations: %w", err)
		}
		return gormDB, adapter, nil
	})
	container.Provide(store.NewStore)
	container.Provide(logging.NewLogger)
	container.Provide(crypto.NewService)
	container.Provide(repository.NewAuthTokenRepository)
	container.Provide(repository.NewGroupRepository)
	container.Provide(repository.NewKeyRepository)
	// Repository 接口绑定
	//container.Provide(func(r *repository.gormKeyRepository) repository.KeyRepository { return r })
	//container.Provide(func(r *repository.GormGroupRepository) repository.GroupRepository { return r })

	// SettingsManager.
	container.Provide(settings.NewSettingsManager)
	// 基于SettingsManager, 提供一个标准的、安全的“数据插座” 让模块只依赖所需的数据，而非整个管理器。
	container.Provide(func(sm *settings.SettingsManager) *models.SystemSettings { return sm.GetSettings() })

	// =========== 阶段二: 核心服务层 (Services) ===========
	container.Provide(service.NewDBLogWriterService)
	container.Provide(service.NewSecurityService)
	container.Provide(crypto.NewService)
	container.Provide(service.NewKeyImportService)
	container.Provide(service.NewKeyValidationService)
	container.Provide(service.NewTokenManager)
	container.Provide(service.NewAPIKeyService)
	container.Provide(service.NewGroupManager)
	container.Provide(service.NewResourceService)
	container.Provide(service.NewAnalyticsService)
	container.Provide(service.NewLogService)
	container.Provide(service.NewHealthCheckService)
	container.Provide(service.NewStatsService)
	container.Provide(service.NewDashboardQueryService)
	container.Provide(scheduler.NewScheduler)
	container.Provide(task.NewTask)

	// --- Task Reporter ---
	container.Provide(func(t *task.Task) task.Reporter { return t })
	// --- Syncer & Loader for GroupManager ---
	container.Provide(service.NewGroupManagerLoader)
	// 为GroupManager配置Syncer
	container.Provide(func(loader syncer.LoaderFunc[service.GroupManagerCacheData], store store.Store, logger *logrus.Logger) (*syncer.CacheSyncer[service.GroupManagerCacheData], error) {
		const groupUpdateChannel = "groups:cache_invalidation"
		return syncer.NewCacheSyncer(loader, store, groupUpdateChannel, logger)
	})

	// =========== 阶段三: 适配器与处理器层 (Handlers & Adapters) ===========

	container.Provide(channel.NewGeminiChannel)
	container.Provide(func(ch *channel.GeminiChannel) channel.ChannelProxy { return ch })

	// --- API Handlers ---
	container.Provide(handlers.NewAPIKeyHandler)
	container.Provide(handlers.NewKeyGroupHandler)
	container.Provide(handlers.NewTokensHandler)
	container.Provide(handlers.NewLogHandler)
	container.Provide(handlers.NewSettingHandler)
	container.Provide(handlers.NewDashboardHandler)
	container.Provide(handlers.NewAPIAuthHandler)
	container.Provide(handlers.NewProxyHandler)
	container.Provide(handlers.NewTaskHandler)

	// --- Domain Modules ---
	container.Provide(upstream.NewModule)
	container.Provide(proxy.NewModule)

	// --- Web Page Handlers ---
	container.Provide(webhandlers.NewWebAuthHandler)
	container.Provide(webhandlers.NewPageHandler)

	// =========== 顶层应用层 (Application) ===========
	container.Provide(router.NewRouter)
	container.Provide(app.NewApp)

	return container, nil
}
