package api

import (
	"context"
	"net/http"
	"net/http/pprof"

	"git.huangwc.com/pig/pig-farm-controller/internal/app/middleware"
	"git.huangwc.com/pig/pig-farm-controller/internal/infra/logs"

	"github.com/labstack/echo/v4"
	echoSwagger "github.com/swaggo/echo-swagger"
)

// setupRoutes 设置所有 API 路由
// 在此方法中，使用已初始化的控制器实例将其路由注册到 Echo 引擎中。
func (a *API) setupRoutes() {
	logger := logs.TraceLogger(a.Ctx, a.Ctx, "SetupRoutes")

	// --- Public Routes ---
	// 这些路由不需要身份验证

	// 健康检查路由
	a.echo.GET("/healthz", a.healthController.Healthz)
	a.echo.GET("/readyz", a.healthController.Readyz)
	logger.Debug("公开接口注册成功：健康检查")

	// 用户注册和登录
	a.echo.POST("/api/v1/users", a.userController.CreateUser)  // 注册新用户
	a.echo.POST("/api/v1/users/login", a.userController.Login) // 用户登录
	logger.Debug("公开接口注册成功：用户注册、登录")

	// 注册 pprof 路由
	pprofGroup := a.echo.Group("/debug/pprof")
	{
		pprofGroup.GET("/", echo.WrapHandler(http.HandlerFunc(pprof.Index)))          // pprof 索引页
		pprofGroup.GET("/cmdline", echo.WrapHandler(http.HandlerFunc(pprof.Cmdline))) // pprof 命令行参数
		pprofGroup.GET("/profile", echo.WrapHandler(http.HandlerFunc(pprof.Profile))) // pprof CPU profile
		pprofGroup.POST("/symbol", echo.WrapHandler(http.HandlerFunc(pprof.Symbol)))  // pprof 符号查找 (POST)
		pprofGroup.GET("/symbol", echo.WrapHandler(http.HandlerFunc(pprof.Symbol)))   // pprof 符号查找 (GET)
		pprofGroup.GET("/trace", echo.WrapHandler(http.HandlerFunc(pprof.Trace)))     // pprof 跟踪
		pprofGroup.GET("/allocs", echo.WrapHandler(pprof.Handler("allocs")))          // pprof 内存分配
		pprofGroup.GET("/block", echo.WrapHandler(pprof.Handler("block")))            // pprof 阻塞
		pprofGroup.GET("/goroutine", echo.WrapHandler(pprof.Handler("goroutine")))
		pprofGroup.GET("/heap", echo.WrapHandler(pprof.Handler("heap")))   // pprof 堆内存
		pprofGroup.GET("/mutex", echo.WrapHandler(pprof.Handler("mutex"))) // pprof 互斥锁
		pprofGroup.GET("/threadcreate", echo.WrapHandler(pprof.Handler("threadcreate")))
	}
	logger.Debug("pprof 接口注册成功")

	// 上行事件监听路由
	a.echo.POST("/upstream", echo.WrapHandler(a.listenHandler.Handler())) // 处理设备上行事件
	logger.Debug("上行事件监听接口注册成功")

	// 添加 Swagger UI 路由, Swagger UI可在 /swagger/index.html 上找到
	a.echo.GET("/swagger/*any", echoSwagger.WrapHandler) // Swagger UI 接口
	logger.Debug("Swagger UI 接口注册成功")

	// --- Authenticated Routes ---
	// 所有在此注册的路由都需要通过 JWT 身份验证
	authGroup := a.echo.Group("/api/v1")
	authGroup.Use(middleware.AuthMiddleware(logs.AddCompName(context.Background(), "AuthMiddleware"), a.tokenGenerator, a.userRepo)) // 1. 身份认证中间件
	authGroup.Use(middleware.AuditLogMiddleware(logs.AddCompName(context.Background(), "AuditLogMiddleware"), a.auditService))       // 2. 审计日志中间件
	{
		// 用户相关路由组
		userGroup := authGroup.Group("/users")
		{
			userGroup.POST("/:id/notifications/test", a.userController.SendTestNotification)
		}
		logger.Debug("用户相关接口注册成功 (需要认证和审计)")

		// 设备相关路由组
		deviceGroup := authGroup.Group("/devices")
		{
			deviceGroup.POST("", a.deviceController.CreateDevice)                     // 创建设备
			deviceGroup.GET("", a.deviceController.ListDevices)                       // 获取设备列表
			deviceGroup.GET("/:id", a.deviceController.GetDevice)                     // 获取单个设备
			deviceGroup.PUT("/:id", a.deviceController.UpdateDevice)                  // 更新设备
			deviceGroup.DELETE("/:id", a.deviceController.DeleteDevice)               // 删除设备
			deviceGroup.POST("/manual-control/:id", a.deviceController.ManualControl) // 手动控制设备
		}
		logger.Debug("设备相关接口注册成功 (需要认证和审计)")

		// 区域主控相关路由组
		areaControllerGroup := authGroup.Group("/area-controllers")
		{
			areaControllerGroup.POST("", a.deviceController.CreateAreaController)       // 创建区域主控
			areaControllerGroup.GET("", a.deviceController.ListAreaControllers)         // 获取区域主控列表
			areaControllerGroup.GET("/:id", a.deviceController.GetAreaController)       // 获取单个区域主控
			areaControllerGroup.PUT("/:id", a.deviceController.UpdateAreaController)    // 更新区域主控
			areaControllerGroup.DELETE("/:id", a.deviceController.DeleteAreaController) // 删除区域主控
		}
		logger.Debug("区域主控相关接口注册成功 (需要认证和审计)")

		// 设备模板相关路由组
		deviceTemplateGroup := authGroup.Group("/device-templates")
		{
			deviceTemplateGroup.POST("", a.deviceController.CreateDeviceTemplate)       // 创建设备模板
			deviceTemplateGroup.GET("", a.deviceController.ListDeviceTemplates)         // 获取设备模板列表
			deviceTemplateGroup.GET("/:id", a.deviceController.GetDeviceTemplate)       // 获取单个设备模板
			deviceTemplateGroup.PUT("/:id", a.deviceController.UpdateDeviceTemplate)    // 更新设备模板
			deviceTemplateGroup.DELETE("/:id", a.deviceController.DeleteDeviceTemplate) // 删除设备模板
		}
		logger.Debug("设备模板相关接口注册成功 (需要认证和审计)")

		// 计划相关路由组
		planGroup := authGroup.Group("/plans")
		{
			planGroup.POST("", a.planController.CreatePlan)          // 创建计划
			planGroup.GET("", a.planController.ListPlans)            // 获取计划列表
			planGroup.GET("/:id", a.planController.GetPlan)          // 获取单个计划
			planGroup.PUT("/:id", a.planController.UpdatePlan)       // 更新计划
			planGroup.DELETE("/:id", a.planController.DeletePlan)    // 删除计划
			planGroup.POST("/:id/start", a.planController.StartPlan) // 启动计划
			planGroup.POST("/:id/stop", a.planController.StopPlan)   // 停止计划
		}
		logger.Debug("计划相关接口注册成功 (需要认证和审计)")

		// 猪舍相关路由组
		pigHouseGroup := authGroup.Group("/pig-houses")
		{
			pigHouseGroup.POST("", a.pigFarmController.CreatePigHouse)       // 创建猪舍
			pigHouseGroup.GET("", a.pigFarmController.ListPigHouses)         // 获取猪舍列表
			pigHouseGroup.GET("/:id", a.pigFarmController.GetPigHouse)       // 获取单个猪舍
			pigHouseGroup.PUT("/:id", a.pigFarmController.UpdatePigHouse)    // 更新猪舍
			pigHouseGroup.DELETE("/:id", a.pigFarmController.DeletePigHouse) // 删除猪舍
		}
		logger.Debug("猪舍相关接口注册成功 (需要认证和审计)")

		// 猪圈相关路由组
		penGroup := authGroup.Group("/pens")
		{
			penGroup.POST("", a.pigFarmController.CreatePen)                 // 创建猪圈
			penGroup.GET("", a.pigFarmController.ListPens)                   // 获取猪圈列表
			penGroup.GET("/:id", a.pigFarmController.GetPen)                 // 获取单个猪圈
			penGroup.PUT("/:id", a.pigFarmController.UpdatePen)              // 更新猪圈
			penGroup.DELETE("/:id", a.pigFarmController.DeletePen)           // 删除猪圈
			penGroup.PUT("/:id/status", a.pigFarmController.UpdatePenStatus) // 更新猪圈状态
		}
		logger.Debug("猪圈相关接口注册成功 (需要认证和审计)")

		// 猪群相关路由组
		pigBatchGroup := authGroup.Group("/pig-batches")
		{
			pigBatchGroup.POST("", a.pigBatchController.CreatePigBatch)                                                   // 创建猪群
			pigBatchGroup.GET("", a.pigBatchController.ListPigBatches)                                                    // 获取猪群列表
			pigBatchGroup.GET("/:id", a.pigBatchController.GetPigBatch)                                                   // 获取单个猪群
			pigBatchGroup.PUT("/:id", a.pigBatchController.UpdatePigBatch)                                                // 更新猪群
			pigBatchGroup.DELETE("/:id", a.pigBatchController.DeletePigBatch)                                             // 删除猪群
			pigBatchGroup.POST("/assign-pens/:id", a.pigBatchController.AssignEmptyPensToBatch)                           // 为猪群分配空栏
			pigBatchGroup.POST("/reclassify-pen/:fromBatchID", a.pigBatchController.ReclassifyPenToNewBatch)              // 将猪栏划拨到新群
			pigBatchGroup.DELETE("/remove-pen/:penID/:batchID", a.pigBatchController.RemoveEmptyPenFromBatch)             // 从猪群移除空栏
			pigBatchGroup.POST("/move-pigs-into-pen/:id", a.pigBatchController.MovePigsIntoPen)                           // 将猪只从“虚拟库存”移入指定猪栏
			pigBatchGroup.POST("/sell-pigs/:id", a.pigBatchController.SellPigs)                                           // 处理卖猪业务
			pigBatchGroup.POST("/buy-pigs/:id", a.pigBatchController.BuyPigs)                                             // 处理买猪业务
			pigBatchGroup.POST("/transfer-across-batches/:sourceBatchID", a.pigBatchController.TransferPigsAcrossBatches) // 跨猪群调栏
			pigBatchGroup.POST("/transfer-within-batch/:id", a.pigBatchController.TransferPigsWithinBatch)                // 群内调栏
			pigBatchGroup.POST("/record-sick-pigs/:id", a.pigBatchController.RecordSickPigs)                              // 记录新增病猪事件
			pigBatchGroup.POST("/record-sick-pig-recovery/:id", a.pigBatchController.RecordSickPigRecovery)               // 记录病猪康复事件
			pigBatchGroup.POST("/record-sick-pig-death/:id", a.pigBatchController.RecordSickPigDeath)                     // 记录病猪死亡事件
			pigBatchGroup.POST("/record-sick-pig-cull/:id", a.pigBatchController.RecordSickPigCull)                       // 记录病猪淘汰事件
			pigBatchGroup.POST("/record-death/:id", a.pigBatchController.RecordDeath)                                     // 记录正常猪只死亡事件
			pigBatchGroup.POST("/record-cull/:id", a.pigBatchController.RecordCull)                                       // 记录正常猪只淘汰事件
		}
		logger.Debug("猪群相关接口注册成功 (需要认证和审计)")

		// 数据监控相关路由组
		monitorGroup := authGroup.Group("/monitor")
		{
			monitorGroup.GET("/sensor-data", a.monitorController.ListSensorData)
			monitorGroup.GET("/device-command-logs", a.monitorController.ListDeviceCommandLogs)
			monitorGroup.GET("/plan-execution-logs", a.monitorController.ListPlanExecutionLogs)
			monitorGroup.GET("/task-execution-logs", a.monitorController.ListTaskExecutionLogs)
			monitorGroup.GET("/pending-collections", a.monitorController.ListPendingCollections)
			monitorGroup.GET("/user-action-logs", a.monitorController.ListUserActionLogs)
			monitorGroup.GET("/medication-logs", a.monitorController.ListMedicationLogs)
			monitorGroup.GET("/pig-batch-logs", a.monitorController.ListPigBatchLogs)
			monitorGroup.GET("/weighing-batches", a.monitorController.ListWeighingBatches)
			monitorGroup.GET("/weighing-records", a.monitorController.ListWeighingRecords)
			monitorGroup.GET("/pig-transfer-logs", a.monitorController.ListPigTransferLogs)
			monitorGroup.GET("/pig-sick-logs", a.monitorController.ListPigSickLogs)
			monitorGroup.GET("/pig-purchases", a.monitorController.ListPigPurchases)
			monitorGroup.GET("/pig-sales", a.monitorController.ListPigSales)
			monitorGroup.GET("/notifications", a.monitorController.ListNotifications)
		}
		logger.Debug("数据监控相关接口注册成功 (需要认证和审计)")

		// 告警相关路由组
		alarmGroup := authGroup.Group("/alarm")
		{
			thresholdGroup := alarmGroup.Group("/threshold")
			{
				thresholdGroup.POST("/:id/snooze", a.alarmController.SnoozeThresholdAlarm)              // 忽略阈值告警
				thresholdGroup.POST("/:id/cancel-snooze", a.alarmController.CancelSnoozeThresholdAlarm) // 取消忽略阈值告警
				thresholdGroup.GET("/active-alarms", a.alarmController.ListActiveAlarms)                // 获取活跃告警
				thresholdGroup.GET("/historical-alarms", a.alarmController.ListHistoricalAlarms)        // 获取历史告警

				// 设备阈值告警配置
				thresholdGroup.GET("/device", a.alarmController.ListDeviceThresholdAlarms)
				thresholdGroup.POST("/device", a.alarmController.CreateDeviceThresholdAlarm)
				thresholdGroup.GET("/device/:task_id", a.alarmController.GetDeviceThresholdAlarm)
				thresholdGroup.PUT("/device/:task_id", a.alarmController.UpdateDeviceThresholdAlarm)
				thresholdGroup.DELETE("/device/:task_id", a.alarmController.DeleteDeviceThresholdAlarm)

				// 区域阈值告警配置
				thresholdGroup.GET("/area", a.alarmController.ListAreaThresholdAlarms)
				thresholdGroup.POST("/area", a.alarmController.CreateAreaThresholdAlarm)
				thresholdGroup.GET("/area/:task_id", a.alarmController.GetAreaThresholdAlarm)
				thresholdGroup.PUT("/area/:task_id", a.alarmController.UpdateAreaThresholdAlarm)
				thresholdGroup.DELETE("/area/:task_id", a.alarmController.DeleteAreaThresholdAlarm)

			}
		}
		logger.Debug("告警相关接口注册成功 (需要认证和审计)")

		// 饲料管理相关路由组
		feedGroup := authGroup.Group("/feed")
		{
			// 营养种类 (Nutrient) 路由
			feedGroup.POST("/nutrients", a.feedController.CreateNutrient)
			feedGroup.PUT("/nutrients/:id", a.feedController.UpdateNutrient)
			feedGroup.DELETE("/nutrients/:id", a.feedController.DeleteNutrient)
			feedGroup.GET("/nutrients/:id", a.feedController.GetNutrient)
			feedGroup.GET("/nutrients", a.feedController.ListNutrients)

			// 原料 (RawMaterial) 路由
			feedGroup.POST("/raw-materials", a.feedController.CreateRawMaterial)
			feedGroup.PUT("/raw-materials/:id", a.feedController.UpdateRawMaterial)
			feedGroup.DELETE("/raw-materials/:id", a.feedController.DeleteRawMaterial)
			feedGroup.GET("/raw-materials/:id", a.feedController.GetRawMaterial)
			feedGroup.GET("/raw-materials", a.feedController.ListRawMaterials)

			// 猪品种 (PigBreed) 路由
			feedGroup.POST("/pig-breeds", a.feedController.CreatePigBreed)
			feedGroup.PUT("/pig-breeds/:id", a.feedController.UpdatePigBreed)
			feedGroup.DELETE("/pig-breeds/:id", a.feedController.DeletePigBreed)
			feedGroup.GET("/pig-breeds/:id", a.feedController.GetPigBreed)
			feedGroup.GET("/pig-breeds", a.feedController.ListPigBreeds)

			// 猪年龄阶段 (PigAgeStage) 路由
			feedGroup.POST("/pig-age-stages", a.feedController.CreatePigAgeStage)
			feedGroup.PUT("/pig-age-stages/:id", a.feedController.UpdatePigAgeStage)
			feedGroup.DELETE("/pig-age-stages/:id", a.feedController.DeletePigAgeStage)
			feedGroup.GET("/pig-age-stages/:id", a.feedController.GetPigAgeStage)
			feedGroup.GET("/pig-age-stages", a.feedController.ListPigAgeStages)

			// 猪类型 (PigType) 路由
			feedGroup.POST("/pig-types", a.feedController.CreatePigType)
			feedGroup.PUT("/pig-types/:id", a.feedController.UpdatePigType)
			feedGroup.DELETE("/pig-types/:id", a.feedController.DeletePigType)
			feedGroup.GET("/pig-types/:id", a.feedController.GetPigType)
			feedGroup.GET("/pig-types", a.feedController.ListPigTypes)
		}
		logger.Debug("饲料管理相关接口注册成功 (需要认证和审计)")
	}

	logger.Debug("所有接口注册成功")
}
