package api

import (
	"github.com/bigtux/ophion/internal/ai"
	"github.com/gofiber/fiber/v2"
)

// AIHandlers handlers para endpoints de IA
type AIHandlers struct {
	copilot      *ai.OphionCopilot
	autoHealer   *ai.AutoHealer
	smartAlerts  *ai.SmartAlertEngine
	insights     *ai.InsightsEngine
}

// NewAIHandlers cria handlers de IA
func NewAIHandlers(engine *ai.AIEngine) *AIHandlers {
	return &AIHandlers{
		copilot:     ai.NewOphionCopilot(engine),
		autoHealer:  ai.NewAutoHealer(engine, ai.AutoHealConfig{
			Enabled: true,
			DryRun:  true, // Começa em dry-run por segurança
		}),
		smartAlerts: ai.NewSmartAlertEngine(engine),
		insights:    ai.NewInsightsEngine(engine),
	}
}

// RegisterRoutes registra rotas de IA
func (h *AIHandlers) RegisterRoutes(api fiber.Router) {
	aiGroup := api.Group("/ai")
	
	// Copilot - Chat com IA
	aiGroup.Post("/copilot/chat", h.CopilotChat)
	
	// Auto-Healing
	aiGroup.Post("/autohealing/analyze", h.AnalyzeIncident)
	aiGroup.Post("/autohealing/execute", h.ExecuteHealing)
	
	// Smart Alerts
	aiGroup.Post("/alerts/process", h.ProcessAlert)
	aiGroup.Post("/alerts/correlate", h.CorrelateAlerts)
	
	// Insights
	aiGroup.Get("/insights/daily", h.GetDailyInsights)
	aiGroup.Get("/insights/security", h.GetSecurityInsights)
	aiGroup.Get("/reports/executive", h.GetExecutiveReport)
	
	// Anomaly Detection
	aiGroup.Post("/anomaly/detect", h.DetectAnomaly)
	
	// Predictions
	aiGroup.Get("/predictions/capacity", h.GetCapacityPredictions)
}

// CopilotChat handler para chat com o Copilot
// @Summary Chat with OPHION Copilot
// @Tags AI
// @Accept json
// @Produce json
// @Param request body CopilotChatRequest true "Chat request"
// @Success 200 {object} ai.CopilotResponse
// @Router /api/v1/ai/copilot/chat [post]
func (h *AIHandlers) CopilotChat(c *fiber.Ctx) error {
	var req CopilotChatRequest
	if err := c.BodyParser(&req); err != nil {
		return c.Status(400).JSON(fiber.Map{"error": "Invalid request"})
	}

	// Obter contexto do sistema (simplificado)
	sysCtx := ai.SystemContext{
		TotalHosts:    10,
		ActiveAlerts:  2,
		OpenIncidents: 0,
	}

	response, err := h.copilot.Chat(c.Context(), req.SessionID, req.Message, sysCtx)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}

	return c.JSON(response)
}

// AnalyzeIncident analisa incidente para auto-healing
// @Summary Analyze incident for auto-healing
// @Tags AI
// @Accept json
// @Produce json
// @Param request body ai.Incident true "Incident data"
// @Success 200 {object} ai.HealingPlan
// @Router /api/v1/ai/autohealing/analyze [post]
func (h *AIHandlers) AnalyzeIncident(c *fiber.Ctx) error {
	var incident ai.Incident
	if err := c.BodyParser(&incident); err != nil {
		return c.Status(400).JSON(fiber.Map{"error": "Invalid request"})
	}

	plan, err := h.autoHealer.Analyze(c.Context(), incident)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}

	return c.JSON(plan)
}

// ExecuteHealing executa plano de auto-healing
// @Summary Execute auto-healing plan
// @Tags AI
// @Accept json
// @Produce json
// @Param request body ai.HealingPlan true "Healing plan"
// @Success 200 {object} ai.HealingResult
// @Router /api/v1/ai/autohealing/execute [post]
func (h *AIHandlers) ExecuteHealing(c *fiber.Ctx) error {
	var plan ai.HealingPlan
	if err := c.BodyParser(&plan); err != nil {
		return c.Status(400).JSON(fiber.Map{"error": "Invalid request"})
	}

	result, err := h.autoHealer.Execute(c.Context(), &plan)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}

	return c.JSON(result)
}

// ProcessAlert processa alerta com IA
// @Summary Process alert with AI enrichment
// @Tags AI
// @Accept json
// @Produce json
// @Param request body ProcessAlertRequest true "Alert data"
// @Success 200 {object} ai.SmartAlert
// @Router /api/v1/ai/alerts/process [post]
func (h *AIHandlers) ProcessAlert(c *fiber.Ctx) error {
	var req ProcessAlertRequest
	if err := c.BodyParser(&req); err != nil {
		return c.Status(400).JSON(fiber.Map{"error": "Invalid request"})
	}

	alertCtx := ai.AlertContext{
		IsBusinessHours: true,
	}

	smart, err := h.smartAlerts.ProcessAlert(c.Context(), req.Alert, alertCtx)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}

	return c.JSON(smart)
}

// CorrelateAlerts correlaciona alertas relacionados
// @Summary Correlate related alerts
// @Tags AI
// @Accept json
// @Produce json
// @Param request body CorrelateRequest true "Alerts to correlate"
// @Success 200 {object} ai.AlertCorrelation
// @Router /api/v1/ai/alerts/correlate [post]
func (h *AIHandlers) CorrelateAlerts(c *fiber.Ctx) error {
	var req CorrelateRequest
	if err := c.BodyParser(&req); err != nil {
		return c.Status(400).JSON(fiber.Map{"error": "Invalid request"})
	}

	correlation, err := h.smartAlerts.CorrelateAlerts(c.Context(), req.Alerts)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}

	if correlation == nil {
		return c.JSON(fiber.Map{"correlated": false})
	}

	return c.JSON(correlation)
}

// GetDailyInsights retorna insights diários
// @Summary Get daily AI insights
// @Tags AI
// @Produce json
// @Success 200 {object} ai.DailyInsights
// @Router /api/v1/ai/insights/daily [get]
func (h *AIHandlers) GetDailyInsights(c *fiber.Ctx) error {
	// TODO: Buscar dados reais do sistema
	data := ai.DailyData{
		Period:     "últimas 24h",
		TotalHosts: 10,
	}

	insights, err := h.insights.GenerateDailyInsights(c.Context(), data)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}

	return c.JSON(insights)
}

// GetSecurityInsights retorna insights de segurança
// @Summary Get security insights
// @Tags AI
// @Produce json
// @Success 200 {array} ai.SecurityInsight
// @Router /api/v1/ai/insights/security [get]
func (h *AIHandlers) GetSecurityInsights(c *fiber.Ctx) error {
	data := ai.SecurityData{}

	insights, err := h.insights.DetectSecurityAnomalies(c.Context(), data)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}

	return c.JSON(insights)
}

// GetExecutiveReport retorna relatório executivo
// @Summary Get executive report
// @Tags AI
// @Produce json
// @Param period query string false "Report period (weekly/monthly)"
// @Success 200 {object} ai.ExecutiveReport
// @Router /api/v1/ai/reports/executive [get]
func (h *AIHandlers) GetExecutiveReport(c *fiber.Ctx) error {
	period := c.Query("period", "weekly")
	
	data := ai.ReportData{
		Period: period,
	}

	report, err := h.insights.GenerateExecutiveReport(c.Context(), period, data)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}

	return c.JSON(report)
}

// DetectAnomaly detecta anomalias em métricas
// @Summary Detect anomalies in metrics
// @Tags AI
// @Accept json
// @Produce json
// @Param request body ai.MetricsData true "Metrics data"
// @Success 200 {object} ai.AnomalyResult
// @Router /api/v1/ai/anomaly/detect [post]
func (h *AIHandlers) DetectAnomaly(c *fiber.Ctx) error {
	var data ai.MetricsData
	if err := c.BodyParser(&data); err != nil {
		return c.Status(400).JSON(fiber.Map{"error": "Invalid request"})
	}

	// TODO: Usar o engine diretamente
	return c.JSON(fiber.Map{"message": "Anomaly detection endpoint"})
}

// GetCapacityPredictions retorna previsões de capacidade
// @Summary Get capacity predictions
// @Tags AI
// @Produce json
// @Param host query string false "Filter by host"
// @Success 200 {array} ai.PredictionResult
// @Router /api/v1/ai/predictions/capacity [get]
func (h *AIHandlers) GetCapacityPredictions(c *fiber.Ctx) error {
	// TODO: Implementar busca de previsões
	return c.JSON([]fiber.Map{})
}

// === Request/Response types ===

// CopilotChatRequest requisição para chat do copilot
type CopilotChatRequest struct {
	SessionID string `json:"session_id"`
	Message   string `json:"message"`
}

// ProcessAlertRequest requisição para processar alerta
type ProcessAlertRequest struct {
	Alert ai.RawAlert `json:"alert"`
}

// CorrelateRequest requisição para correlacionar alertas
type CorrelateRequest struct {
	Alerts []ai.SmartAlert `json:"alerts"`
}
