/*
 * Project: Video Sharing Platform
 * Year: 2026
 * Developed by: Molla Samser (Founder of RSK World)
 * 
 * Video recommendation engine and analytics.
 */

package main

import (
	"math/rand"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

type Recommendation struct {
	VideoID    int     `json:"video_id"`
	Title      string  `json:"title"`
	Creator    string  `json:"creator"`
	Thumbnail  string  `json:"thumbnail"`
	Duration   string  `json:"duration"`
	Views      string  `json:"views"`
	Score      float64 `json:"score"`
	Reason     string  `json:"reason"`
}

type TrendingVideo struct {
	VideoID      int    `json:"video_id"`
	Title        string `json:"title"`
	Creator      string `json:"creator"`
	Views        string `json:"views"`
	Growth       string `json:"growth"`
	Category     string `json:"category"`
	TrendingRank int    `json:"trending_rank"`
}

type WatchHistory struct {
	VideoID    int       `json:"video_id"`
	WatchedAt  time.Time `json:"watched_at"`
	Duration   int       `json:"duration_watched"` // seconds
	TotalTime  int       `json:"total_duration"`   // seconds
	Completed  bool      `json:"completed"`
}

var watchHistory = []WatchHistory{
	{VideoID: 1, WatchedAt: time.Now().Add(-2 * time.Hour), Duration: 600, TotalTime: 924, Completed: false},
	{VideoID: 2, WatchedAt: time.Now().Add(-24 * time.Hour), Duration: 1800, TotalTime: 1800, Completed: true},
}

func GetRecommendations(c *gin.Context) {
	userID := c.GetInt("user_id")
	
	// Simulate recommendation algorithm
	recommendations := generateRecommendations(userID)
	
	c.JSON(http.StatusOK, gin.H{
		"recommendations": recommendations,
		"algorithm": "collaborative_filtering_v2",
		"updated_at": time.Now(),
	})
}

func GetTrendingVideos(c *gin.Context) {
	category := c.Query("category")
	timeframe := c.Query("timeframe") // daily, weekly, monthly
	
	trending := generateTrendingVideos(category, timeframe)
	
	c.JSON(http.StatusOK, gin.H{
		"trending": trending,
		"category": category,
		"timeframe": timeframe,
		"updated_at": time.Now(),
	})
}

func GetWatchHistory(c *gin.Context) {
	userID := c.GetInt("user_id")
	if userID == 0 {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentication required"})
		return
	}

	// Filter history by user (mock implementation)
	userHistory := watchHistory
	
	c.JSON(http.StatusOK, gin.H{
		"history": userHistory,
		"total_watched": len(userHistory),
		"total_hours": calculateTotalWatchTime(userHistory),
	})
}

func AddToWatchHistory(c *gin.Context) {
	userID := c.GetInt("user_id")
	if userID == 0 {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentication required"})
		return
	}

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

	history.WatchedAt = time.Now()
	watchHistory = append(watchHistory, history)

	c.JSON(http.StatusCreated, gin.H{
		"status": "added_to_history",
		"history": history,
	})
}

func GetSimilarVideos(c *gin.Context) {
	videoID := c.Param("video_id")
	
	// Find similar videos based on tags, creator, category
	similar := generateSimilarVideos(videoID)
	
	c.JSON(http.StatusOK, gin.H{
		"similar_videos": similar,
		"video_id": videoID,
		"count": len(similar),
	})
}

func generateRecommendations(userID int) []Recommendation {
	recommendations := []Recommendation{
		{
			VideoID:    3,
			Title:      "Advanced Go Concurrency Patterns",
			Creator:    "RSK World Team",
			Thumbnail:  "https://images.unsplash.com/photo-1461749280684-dccba630e2f6?auto=format&fit=crop&q=80&w=800",
			Duration:   "25:15",
			Views:      "125K",
			Score:      0.95,
			Reason:     "Because you watched Go tutorials",
		},
		{
			VideoID:    4,
			Title:      "Building Scalable Video Platforms",
			Creator:    "Molla Samser",
			Thumbnail:  "https://images.unsplash.com/photo-1551288049-bebda4e38f71?auto=format&fit=crop&q=80&w=800",
			Duration:   "18:30",
			Views:      "89K",
			Score:      0.88,
			Reason:     "Popular in your network",
		},
		{
			VideoID:    5,
			Title:      "Live Streaming Architecture 2026",
			Creator:    "Tech Masters",
			Thumbnail:  "https://images.unsplash.com/photo-1573168715888-a6c0f5aa293a?auto=format&fit=crop&q=80&w=800",
			Duration:   "32:45",
			Views:      "234K",
			Score:      0.82,
			Reason:     "Trending in Technology",
		},
	}

	// Shuffle for variety
	rand.Seed(time.Now().UnixNano())
	rand.Shuffle(len(recommendations), func(i, j int) {
		recommendations[i], recommendations[j] = recommendations[j], recommendations[i]
	})

	return recommendations
}

func generateTrendingVideos(category, timeframe string) []TrendingVideo {
	trending := []TrendingVideo{
		{
			VideoID:      1,
			Title:        "Building High-Performance Media Systems with Go",
			Creator:      "Molla Samser",
			Views:        "1.2M",
			Growth:       "+45%",
			Category:     "Tutorials",
			TrendingRank: 1,
		},
		{
			VideoID:      2,
			Title:        "Live: Advanced Video Processing Techniques",
			Creator:      "Rima Khatun",
			Views:        "450K",
			Growth:       "+32%",
			Category:     "Live",
			TrendingRank: 2,
		},
		{
			VideoID:      3,
			Title:        "Mastering FFmpeg for HLS Streaming",
			Creator:      "RSK World Team",
			Views:        "89K",
			Growth:       "+28%",
			Category:     "Tutorials",
			TrendingRank: 3,
		},
	}

	// Filter by category if specified
	if category != "" && category != "All" {
		filtered := []TrendingVideo{}
		for _, video := range trending {
			if video.Category == category {
				filtered = append(filtered, video)
			}
		}
		trending = filtered
	}

	return trending
}

func generateSimilarVideos(videoID string) []Video {
	// Mock similar videos based on the current video
	similarVideos := []Video{
		{
			ID:          5,
			Title:       "Video Processing Best Practices",
			Description: "Learn the best practices for video processing",
			Creator:     "Tech Experts",
			URL:         "/static/vid5.mp4",
			Tags:        []string{"video", "processing", "best-practices"},
		},
		{
			ID:          6,
			Title:       "Streaming Protocols Comparison",
			Description: "HLS vs DASH vs WebRTC comparison",
			Creator:     "Stream Masters",
			URL:         "/static/vid6.mp4",
			Tags:        []string{"streaming", "protocols", "comparison"},
		},
	}

	return similarVideos
}

func calculateTotalWatchTime(history []WatchHistory) float64 {
	totalSeconds := 0
	for _, h := range history {
		totalSeconds += h.Duration
	}
	return float64(totalSeconds) / 3600.0 // Convert to hours
}

func GetAnalytics(c *gin.Context) {
	userID := c.GetInt("user_id")
	if userID == 0 {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentication required"})
		return
	}

	// Mock analytics data
	analytics := map[string]interface{}{
		"views_today":       15420,
		"views_this_week":   108500,
		"views_this_month":  425000,
		"subscribers_gained": 1250,
		"watch_time_hours":  892.5,
		"engagement_rate":  "12.5%",
		"top_performing_video": map[string]interface{}{
			"title": "Building High-Performance Media Systems with Go",
			"views": "1.2M",
			"engagement": "15.2%",
		},
		"demographics": map[string]interface{}{
			"age_groups": map[string]int{"18-24": 25, "25-34": 45, "35-44": 20, "45+": 10},
			"countries": map[string]int{"India": 40, "USA": 25, "UK": 15, "Others": 20},
		},
	}

	c.JSON(http.StatusOK, gin.H{
		"analytics": analytics,
		"user_id": userID,
		"generated_at": time.Now(),
	})
}
