package handlers

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

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

// WorkshopHandlers handles workshop session HTTP requests
type WorkshopHandlers struct {
	store *workshop.Store
}

// NewWorkshopHandlers creates new workshop handlers
func NewWorkshopHandlers(store *workshop.Store) *WorkshopHandlers {
	return &WorkshopHandlers{store: store}
}

// ============================================================================
// Session Management
// ============================================================================

// CreateSession creates a new workshop session
// POST /sdk/v1/workshops
func (h *WorkshopHandlers) CreateSession(c *gin.Context) {
	var req workshop.CreateSessionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	tenantID := rbac.GetTenantID(c)
	userID := rbac.GetUserID(c)

	session := &workshop.Session{
		TenantID:       tenantID,
		Title:          req.Title,
		Description:    req.Description,
		SessionType:    req.SessionType,
		WizardSchema:   req.WizardSchema,
		Status:         workshop.SessionStatusDraft,
		CurrentStep:    1,
		TotalSteps:     10, // Default, will be updated when wizard is loaded
		ScheduledStart: req.ScheduledStart,
		ScheduledEnd:   req.ScheduledEnd,
		AssessmentID:   req.AssessmentID,
		RoadmapID:      req.RoadmapID,
		PortfolioID:    req.PortfolioID,
		Settings:       req.Settings,
		CreatedBy:      userID,
	}

	// Set default settings if not provided
	if !session.Settings.AllowBackNavigation {
		session.Settings.AllowBackNavigation = true
	}
	if !session.Settings.AllowNotes {
		session.Settings.AllowNotes = true
	}
	if !session.Settings.AutoSave {
		session.Settings.AutoSave = true
	}

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

	// Add creator as facilitator
	facilitator := &workshop.Participant{
		SessionID:  session.ID,
		UserID:     &userID,
		Name:       "Session Owner",
		Role:       workshop.ParticipantRoleFacilitator,
		CanEdit:    true,
		CanComment: true,
		CanApprove: true,
	}
	h.store.AddParticipant(c.Request.Context(), facilitator)

	c.JSON(http.StatusCreated, workshop.CreateSessionResponse{
		Session:  *session,
		JoinCode: session.JoinCode,
	})
}

// ListSessions lists workshop sessions
// GET /sdk/v1/workshops
func (h *WorkshopHandlers) ListSessions(c *gin.Context) {
	tenantID := rbac.GetTenantID(c)

	filters := &workshop.SessionFilters{
		Limit: 50,
	}

	if status := c.Query("status"); status != "" {
		filters.Status = workshop.SessionStatus(status)
	}
	if sessionType := c.Query("type"); sessionType != "" {
		filters.SessionType = sessionType
	}

	sessions, err := h.store.ListSessions(c.Request.Context(), tenantID, filters)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"sessions": sessions,
		"total":    len(sessions),
	})
}

// GetSession retrieves a session with details
// GET /sdk/v1/workshops/:id
func (h *WorkshopHandlers) GetSession(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
	}

	// Get responses for current step
	stepNumber := summary.Session.CurrentStep
	responses, _ := h.store.GetResponses(c.Request.Context(), id, &stepNumber)

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

	c.JSON(http.StatusOK, gin.H{
		"session":       summary.Session,
		"participants":  summary.Participants,
		"step_progress": summary.StepProgress,
		"responses":     responses,
		"stats":         stats,
		"progress":      summary.OverallProgress,
	})
}

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

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

	var req workshop.CreateSessionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	session.Title = req.Title
	session.Description = req.Description
	session.ScheduledStart = req.ScheduledStart
	session.ScheduledEnd = req.ScheduledEnd
	session.Settings = req.Settings

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

	c.JSON(http.StatusOK, gin.H{"session": session})
}

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

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

	c.JSON(http.StatusOK, gin.H{"message": "session deleted"})
}

// ============================================================================
// Session Status Control
// ============================================================================

// StartSession starts a workshop session
// POST /sdk/v1/workshops/:id/start
func (h *WorkshopHandlers) StartSession(c *gin.Context) {
	id, err := uuid.Parse(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid session ID"})
		return
	}

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

	if session.Status != workshop.SessionStatusDraft && session.Status != workshop.SessionStatusScheduled && session.Status != workshop.SessionStatusPaused {
		c.JSON(http.StatusBadRequest, gin.H{"error": "session cannot be started from current state"})
		return
	}

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

	// Initialize first step progress
	h.store.UpdateStepProgress(c.Request.Context(), id, 1, "in_progress", 0)

	session.Status = workshop.SessionStatusActive
	now := time.Now().UTC()
	session.ActualStart = &now

	c.JSON(http.StatusOK, gin.H{"session": session, "message": "session started"})
}

// PauseSession pauses a workshop session
// POST /sdk/v1/workshops/:id/pause
func (h *WorkshopHandlers) PauseSession(c *gin.Context) {
	id, err := uuid.Parse(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid session ID"})
		return
	}

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

	c.JSON(http.StatusOK, gin.H{"message": "session paused"})
}

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

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

	// Get final summary
	summary, _ := h.store.GetSessionSummary(c.Request.Context(), id)

	c.JSON(http.StatusOK, gin.H{
		"message": "session completed",
		"summary": summary,
	})
}

// ============================================================================
// Participant Management
// ============================================================================

// JoinSession allows a participant to join a session
// POST /sdk/v1/workshops/join/:code
func (h *WorkshopHandlers) JoinSession(c *gin.Context) {
	code := c.Param("code")

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

	if session.Status == workshop.SessionStatusCompleted || session.Status == workshop.SessionStatusCancelled {
		c.JSON(http.StatusBadRequest, gin.H{"error": "session is no longer active"})
		return
	}

	var req workshop.JoinSessionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// Get user ID if authenticated
	var userID *uuid.UUID
	if id := rbac.GetUserID(c); id != uuid.Nil {
		userID = &id
	}

	// Check if authentication is required
	if session.RequireAuth && userID == nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "authentication required to join this session"})
		return
	}

	participant := &workshop.Participant{
		SessionID:  session.ID,
		UserID:     userID,
		Name:       req.Name,
		Email:      req.Email,
		Role:       req.Role,
		Department: req.Department,
		CanEdit:    true,
		CanComment: true,
	}

	if participant.Role == "" {
		participant.Role = workshop.ParticipantRoleStakeholder
	}

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

	c.JSON(http.StatusOK, workshop.JoinSessionResponse{
		Participant: *participant,
		Session:     *session,
	})
}

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

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

	c.JSON(http.StatusOK, gin.H{
		"participants": participants,
		"total":        len(participants),
	})
}

// LeaveSession removes a participant from a session
// POST /sdk/v1/workshops/:id/leave
func (h *WorkshopHandlers) LeaveSession(c *gin.Context) {
	var req struct {
		ParticipantID uuid.UUID `json:"participant_id"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := h.store.LeaveSession(c.Request.Context(), req.ParticipantID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "left session"})
}

// ============================================================================
// Wizard Navigation & Responses
// ============================================================================

// SubmitResponse submits a response to a question
// POST /sdk/v1/workshops/:id/responses
func (h *WorkshopHandlers) SubmitResponse(c *gin.Context) {
	sessionID, err := uuid.Parse(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid session ID"})
		return
	}

	var req workshop.SubmitResponseRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// Get participant ID from request or context
	participantID, err := uuid.Parse(c.GetHeader("X-Participant-ID"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "participant ID required"})
		return
	}

	// Determine value type
	valueType := "string"
	switch req.Value.(type) {
	case bool:
		valueType = "boolean"
	case float64:
		valueType = "number"
	case []interface{}:
		valueType = "array"
	case map[string]interface{}:
		valueType = "object"
	}

	response := &workshop.Response{
		SessionID:     sessionID,
		ParticipantID: participantID,
		StepNumber:    req.StepNumber,
		FieldID:       req.FieldID,
		Value:         req.Value,
		ValueType:     valueType,
		Status:        workshop.ResponseStatusSubmitted,
	}

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

	// Update participant activity
	h.store.UpdateParticipantActivity(c.Request.Context(), participantID)

	c.JSON(http.StatusOK, gin.H{"response": response})
}

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

	var stepNumber *int
	if step := c.Query("step"); step != "" {
		if s, err := strconv.Atoi(step); err == nil {
			stepNumber = &s
		}
	}

	responses, err := h.store.GetResponses(c.Request.Context(), sessionID, stepNumber)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"responses": responses,
		"total":     len(responses),
	})
}

// AdvanceStep moves the session to the next step
// POST /sdk/v1/workshops/:id/advance
func (h *WorkshopHandlers) AdvanceStep(c *gin.Context) {
	sessionID, err := uuid.Parse(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid session ID"})
		return
	}

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

	if session.CurrentStep >= session.TotalSteps {
		c.JSON(http.StatusBadRequest, gin.H{"error": "already at last step"})
		return
	}

	// Mark current step as completed
	h.store.UpdateStepProgress(c.Request.Context(), sessionID, session.CurrentStep, "completed", 100)

	// Advance to next step
	if err := h.store.AdvanceStep(c.Request.Context(), sessionID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// Initialize next step
	h.store.UpdateStepProgress(c.Request.Context(), sessionID, session.CurrentStep+1, "in_progress", 0)

	c.JSON(http.StatusOK, gin.H{
		"previous_step": session.CurrentStep,
		"current_step":  session.CurrentStep + 1,
		"message":       "advanced to next step",
	})
}

// GoToStep navigates to a specific step (if allowed)
// POST /sdk/v1/workshops/:id/goto
func (h *WorkshopHandlers) GoToStep(c *gin.Context) {
	sessionID, err := uuid.Parse(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid session ID"})
		return
	}

	var req struct {
		StepNumber int `json:"step_number"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

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

	// Check if back navigation is allowed
	if req.StepNumber < session.CurrentStep && !session.Settings.AllowBackNavigation {
		c.JSON(http.StatusBadRequest, gin.H{"error": "back navigation not allowed"})
		return
	}

	// Validate step number
	if req.StepNumber < 1 || req.StepNumber > session.TotalSteps {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid step number"})
		return
	}

	session.CurrentStep = req.StepNumber
	if err := h.store.UpdateSession(c.Request.Context(), session); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"current_step": req.StepNumber,
		"message":      "navigated to step",
	})
}

// ============================================================================
// 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)
}

// ============================================================================
// Participant Management (Extended)
// ============================================================================

// UpdateParticipant updates a participant's info
// PUT /sdk/v1/workshops/:id/participants/:participantId
func (h *WorkshopHandlers) UpdateParticipant(c *gin.Context) {
	participantID, err := uuid.Parse(c.Param("participantId"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid participant ID"})
		return
	}

	var req struct {
		Name       string                  `json:"name"`
		Role       workshop.ParticipantRole `json:"role"`
		Department string                  `json:"department"`
		CanEdit    *bool                   `json:"can_edit,omitempty"`
		CanComment *bool                   `json:"can_comment,omitempty"`
		CanApprove *bool                   `json:"can_approve,omitempty"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

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

	if req.Name != "" {
		participant.Name = req.Name
	}
	if req.Role != "" {
		participant.Role = req.Role
	}
	if req.Department != "" {
		participant.Department = req.Department
	}
	if req.CanEdit != nil {
		participant.CanEdit = *req.CanEdit
	}
	if req.CanComment != nil {
		participant.CanComment = *req.CanComment
	}
	if req.CanApprove != nil {
		participant.CanApprove = *req.CanApprove
	}

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

	c.JSON(http.StatusOK, gin.H{"participant": participant})
}

// RemoveParticipant removes a participant from a session
// DELETE /sdk/v1/workshops/:id/participants/:participantId
func (h *WorkshopHandlers) RemoveParticipant(c *gin.Context) {
	participantID, err := uuid.Parse(c.Param("participantId"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid participant ID"})
		return
	}

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

	c.JSON(http.StatusOK, gin.H{"message": "participant removed"})
}

// ============================================================================
// Comments
// ============================================================================

// AddComment adds a comment to a session
// POST /sdk/v1/workshops/:id/comments
func (h *WorkshopHandlers) AddComment(c *gin.Context) {
	sessionID, err := uuid.Parse(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid session ID"})
		return
	}

	var req struct {
		ParticipantID uuid.UUID  `json:"participant_id"`
		StepNumber    *int       `json:"step_number,omitempty"`
		FieldID       *string    `json:"field_id,omitempty"`
		ResponseID    *uuid.UUID `json:"response_id,omitempty"`
		Text          string     `json:"text"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if req.Text == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "comment text is required"})
		return
	}

	comment := &workshop.Comment{
		SessionID:     sessionID,
		ParticipantID: req.ParticipantID,
		StepNumber:    req.StepNumber,
		FieldID:       req.FieldID,
		ResponseID:    req.ResponseID,
		Text:          req.Text,
	}

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

	c.JSON(http.StatusCreated, gin.H{"comment": comment})
}

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

	var stepNumber *int
	if step := c.Query("step"); step != "" {
		if s, err := strconv.Atoi(step); err == nil {
			stepNumber = &s
		}
	}

	comments, err := h.store.GetComments(c.Request.Context(), sessionID, stepNumber)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"comments": comments,
		"total":    len(comments),
	})
}

// ============================================================================
// 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
}
