package handlers

import (
	"net/http"
	"strconv"
	"time"

	"github.com/breakpilot/ai-compliance-sdk/internal/workshop"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

// ============================================================================
// Statistics
// ============================================================================

// GetSessionStats returns statistics for a session
// GET /sdk/v1/workshops/:id/stats
func (h *WorkshopHandlers) GetSessionStats(c *gin.Context) {
	id, err := uuid.Parse(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid session ID"})
		return
	}

	stats, err := h.store.GetSessionStats(c.Request.Context(), id)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, stats)
}

// GetSessionSummary returns a complete summary of a session
// GET /sdk/v1/workshops/:id/summary
func (h *WorkshopHandlers) GetSessionSummary(c *gin.Context) {
	id, err := uuid.Parse(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid session ID"})
		return
	}

	summary, err := h.store.GetSessionSummary(c.Request.Context(), id)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	if summary == nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "session not found"})
		return
	}

	c.JSON(http.StatusOK, summary)
}

// ============================================================================
// Export
// ============================================================================

// ExportSession exports session data
// GET /sdk/v1/workshops/:id/export
func (h *WorkshopHandlers) ExportSession(c *gin.Context) {
	sessionID, err := uuid.Parse(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid session ID"})
		return
	}

	format := c.DefaultQuery("format", "json")

	// Get complete session data
	summary, err := h.store.GetSessionSummary(c.Request.Context(), sessionID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	if summary == nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "session not found"})
		return
	}

	// Get all responses
	responses, _ := h.store.GetResponses(c.Request.Context(), sessionID, nil)

	// Get all comments
	comments, _ := h.store.GetComments(c.Request.Context(), sessionID, nil)

	// Get stats
	stats, _ := h.store.GetSessionStats(c.Request.Context(), sessionID)

	exportData := gin.H{
		"session":       summary.Session,
		"participants":  summary.Participants,
		"step_progress": summary.StepProgress,
		"responses":     responses,
		"comments":      comments,
		"stats":         stats,
		"exported_at":   time.Now().UTC(),
	}

	switch format {
	case "json":
		c.JSON(http.StatusOK, exportData)
	case "md":
		// Generate markdown format
		md := generateSessionMarkdown(summary, responses, comments, stats)
		c.Header("Content-Type", "text/markdown")
		c.Header("Content-Disposition", "attachment; filename=workshop-session.md")
		c.String(http.StatusOK, md)
	default:
		c.JSON(http.StatusOK, exportData)
	}
}

// generateSessionMarkdown generates a markdown export of the session
func generateSessionMarkdown(summary *workshop.SessionSummary, responses []workshop.Response, comments []workshop.Comment, stats *workshop.SessionStats) string {
	md := "# Workshop Session: " + summary.Session.Title + "\n\n"
	md += "**Type:** " + summary.Session.SessionType + "\n"
	md += "**Status:** " + string(summary.Session.Status) + "\n"
	md += "**Created:** " + summary.Session.CreatedAt.Format("2006-01-02 15:04") + "\n\n"

	if summary.Session.Description != "" {
		md += "## Description\n\n" + summary.Session.Description + "\n\n"
	}

	// Participants
	md += "## Participants\n\n"
	for _, p := range summary.Participants {
		md += "- **" + p.Name + "** (" + string(p.Role) + ")"
		if p.Department != "" {
			md += " - " + p.Department
		}
		md += "\n"
	}
	md += "\n"

	// Progress
	md += "## Progress\n\n"
	md += "**Overall:** " + strconv.Itoa(summary.OverallProgress) + "%\n"
	md += "**Completed Steps:** " + strconv.Itoa(summary.CompletedSteps) + "/" + strconv.Itoa(summary.Session.TotalSteps) + "\n"
	md += "**Total Responses:** " + strconv.Itoa(summary.TotalResponses) + "\n\n"

	// Step progress
	if len(summary.StepProgress) > 0 {
		md += "### Step Progress\n\n"
		for _, sp := range summary.StepProgress {
			md += "- Step " + strconv.Itoa(sp.StepNumber) + ": " + sp.Status + " (" + strconv.Itoa(sp.Progress) + "%)\n"
		}
		md += "\n"
	}

	// Responses by step
	if len(responses) > 0 {
		md += "## Responses\n\n"
		currentStep := 0
		for _, r := range responses {
			if r.StepNumber != currentStep {
				currentStep = r.StepNumber
				md += "### Step " + strconv.Itoa(currentStep) + "\n\n"
			}
			md += "- **" + r.FieldID + ":** "
			switch v := r.Value.(type) {
			case string:
				md += v
			case bool:
				if v {
					md += "Yes"
				} else {
					md += "No"
				}
			default:
				md += "See JSON export for complex value"
			}
			md += "\n"
		}
		md += "\n"
	}

	// Comments
	if len(comments) > 0 {
		md += "## Comments\n\n"
		for _, c := range comments {
			md += "- " + c.Text
			if c.StepNumber != nil {
				md += " (Step " + strconv.Itoa(*c.StepNumber) + ")"
			}
			md += "\n"
		}
		md += "\n"
	}

	md += "---\n*Exported from AI Compliance SDK Workshop Module*\n"

	return md
}
