package routes

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"sort"
	"strconv"
	"strings"
	"time"

	"bitbucket.org/imediabrands/oos-service/internal/cms"
	"bitbucket.org/imediabrands/oos-service/middlewares"
	"github.com/julienschmidt/httprouter"
	"github.com/spf13/viper"
)

var cmsService *cms.Service
var cmsCacheMaxAge int

func cmsCacheControl() string {
	return fmt.Sprintf("public, max-age=%d", cmsCacheMaxAge)
}

func InitCMSService() {
	baseURL := viper.GetString("cms_api_base_url")
	if baseURL == "" {
		baseURL = "https://api.admedia.com/cms/index.php"
	}

	apiKey := viper.GetString("cms_api_key")
	if apiKey == "" {
		log.Fatal("FATAL: cms_api_key is required in config")
	}

	cacheTTL := viper.GetDuration("cms_cache_ttl")
	if cacheTTL == 0 {
		cacheTTL = 24 * time.Hour
	}
	cmsCacheMaxAge = int(cacheTTL.Seconds())

	log.Printf("[INFO] Initializing CMS Service")
	log.Printf("[INFO] Base URL: %s", baseURL)
	log.Printf("[INFO] API Key: %s... (length: %d)", apiKey[:min(10, len(apiKey))], len(apiKey))
	log.Printf("[INFO] Cache TTL: %v", cacheTTL)

	cmsService = cms.NewService(baseURL, apiKey, cacheTTL)
	log.Printf("[INFO] CMS service initialized successfully")
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func DataCategoriesHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		log.Printf("[INFO] DataCategoriesHandler called from %s", req.RemoteAddr)

		// Extract domain from request
		domain := extractDomain(req)
		log.Printf("[INFO] Request domain: %s", domain)

		// A shop site the CMS doesn't list has no categories, not every site's.
		if cmsUnlistedShopSite(req) {
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
			w.Header().Set("Cache-Control", cmsCacheControl())
			fmt.Fprintf(w, `{"data":{%q:[]}}`, middlewares.ResolveToProductionDomain(requestPublicHost(req)))
			return
		}

		data, err := cmsService.GetCategories()
		if err != nil {
			log.Printf("[ERROR] Failed to fetch categories: %v", err)
			http.Error(w, fmt.Sprintf("failed to load categories: %v", err), http.StatusInternalServerError)
			return
		}

		// Parse the JSON response
		var categoryResponse map[string]interface{}
		if err := json.Unmarshal(data, &categoryResponse); err != nil {
			log.Printf("[ERROR] Failed to parse categories JSON: %v", err)
			http.Error(w, "failed to parse categories", http.StatusInternalServerError)
			return
		}

		// Filter by domain if we have a valid domain
		if domain != "" && domain != "localhost" {
			filteredResponse := filterCategoriesByDomain(categoryResponse, domain)
			filteredData, err := json.Marshal(filteredResponse)
			if err != nil {
				log.Printf("[ERROR] Failed to marshal filtered categories: %v", err)
				http.Error(w, "failed to marshal filtered categories", http.StatusInternalServerError)
				return
			}
			log.Printf("[INFO] Filtered categories for domain %s, size: %d bytes", domain, len(filteredData))
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
			w.Header().Set("Cache-Control", cmsCacheControl())
			w.Write(filteredData)
			return
		}

		// Return all categories if no domain or localhost
		log.Printf("[INFO] Returning all categories (no domain filter), size: %d bytes", len(data))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.Header().Set("Cache-Control", cmsCacheControl())
		w.Write(data)
	})
}

func DataCategoryArticlesHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		params := httprouter.ParamsFromContext(req.Context())
		catID := params.ByName("catId")

		if catID == "" {
			http.Error(w, "category ID is required", http.StatusBadRequest)
			return
		}

		// Get query parameters for pagination, search, and optional subcategory.
		query := req.URL.Query()
		page := query.Get("page")
		limit := query.Get("limit")
		search := query.Get("search")
		subcatID := query.Get("subcat_id")

		log.Printf("[INFO] DataCategoryArticlesHandler: catId=%s, subcatId=%s, page=%s, limit=%s, search=%s",
			catID, subcatID, page, limit, search)

		var (
			data []byte
			err  error
		)
		switch {
		case cmsUnlistedShopSite(req):
			// A shop site the CMS doesn't list has no articles.
			data = []byte(`{"data":[]}`)
		case subcatID != "":
			data, err = cmsService.GetSubcategoryArticles(catID, subcatID)
		default:
			data, err = cmsService.GetCategoryArticles(catID)
		}
		if err != nil {
			log.Printf("[ERROR] fetching category articles (catId=%s, subcatId=%s): %v", catID, subcatID, err)
			http.Error(w, "failed to fetch category articles", http.StatusInternalServerError)
			return
		}

		// Parse the response to apply pagination and search
		var response map[string]interface{}
		if err := json.Unmarshal(data, &response); err != nil {
			log.Printf("[ERROR] Failed to parse category articles JSON: %v", err)
			http.Error(w, "failed to parse category articles", http.StatusInternalServerError)
			return
		}

		if articles, ok := response["data"].([]interface{}); ok {
			normalizeImagesAttrList(articles)
		}

		// Apply search and pagination filters
		filteredResponse := applySearchAndPagination(response, search, page, limit)

		filteredData, err := json.Marshal(filteredResponse)
		if err != nil {
			log.Printf("[ERROR] Failed to marshal filtered articles: %v", err)
			http.Error(w, "failed to marshal filtered articles", http.StatusInternalServerError)
			return
		}

		log.Printf("[INFO] Returning filtered articles, size: %d bytes", len(filteredData))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.Header().Set("Cache-Control", cmsCacheControl())
		w.Write(filteredData)
	})
}

func DataArticleHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		params := httprouter.ParamsFromContext(req.Context())
		articleID := params.ByName("id")

		if articleID == "" {
			http.Error(w, "article ID is required", http.StatusBadRequest)
			return
		}

		// Not an article ID ("1760806x"): answer like the CMS does for a missing
		// article, so the app shows its not-found page.
		body := []byte(`{"data":false}`)
		// A shop site the CMS doesn't list has no articles: none is its.
		if isNumericID(articleID) && !cmsUnlistedShopSite(req) {
			data, err := cmsService.GetArticle(articleID)
			if err != nil {
				log.Printf("ERROR fetching article (id=%s): %v", articleID, err)
				http.Error(w, "failed to fetch article", http.StatusInternalServerError)
				return
			}
			// Another site's article stays {"data":false} here, as its page 404s (see articleDetailHandler).
			if meta := articlePageMetaFromCMS(data); meta == (articlePageMeta{}) || articleBelongsToSite(req, meta.Category, articleID) {
				body = normalizeArticleResponse(articleID, data, extractDomain(req), articleURLOptionsFromConfig(middlewares.GetClientConfig(req.Context())))
			}
		}

		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.Header().Set("Cache-Control", cmsCacheControl())
		w.Write(body)
	})
}

// normalizeImagesAttr converts an article's images_attr field from the raw
// JSON-encoded string the CMS returns (e.g. `{"img":{"alt":"..."}}`) into a
// proper nested JSON object/array, so API consumers (the React frontend) can
// read images_attr.img.alt directly instead of each having to JSON-parse a
// string field themselves. Missing or invalid values are left untouched.
func normalizeImagesAttr(article map[string]interface{}) {
	raw, ok := article["images_attr"].(string)
	if !ok || raw == "" {
		return
	}
	var parsed interface{}
	if err := json.Unmarshal([]byte(raw), &parsed); err != nil {
		return
	}
	article["images_attr"] = parsed
}

// normalizeImagesAttrList applies normalizeImagesAttr to every article
// object in a list, skipping any items that aren't the expected shape.
func normalizeImagesAttrList(items []interface{}) {
	for _, item := range items {
		if article, ok := item.(map[string]interface{}); ok {
			normalizeImagesAttr(article)
		}
	}
}

// normalizeArticleResponse parses a single-article CMS response
// (`{"data": {...}}`), normalizes its images_attr field in place and points
// the site's own links inside its content at their final URLs (see
// rewriteInternalLinks; siteDomain is the site's production domain, urlOpts
// how its article URLs are built). If the
// response doesn't parse or match the expected shape, the original bytes are
// returned unchanged so the API never breaks on an unexpected payload.
func normalizeArticleResponse(articleID string, data []byte, siteDomain string, urlOpts articleURLOptions) []byte {
	var response map[string]interface{}
	if err := json.Unmarshal(data, &response); err != nil {
		log.Printf("[WARN] normalizeArticleResponse: failed to parse response for id=%s: %v", articleID, err)
		return data
	}

	article, ok := response["data"].(map[string]interface{})
	if !ok {
		return data
	}
	normalizeImagesAttr(article)
	if content, ok := article["content"].(string); ok {
		article["content"] = rewriteInternalLinks(content, siteDomain, func(id string) string {
			meta, _, _ := loadArticleMeta(id)
			return canonicalArticlePath(forArticleURL(meta, urlOpts), id)
		})
	}

	out, err := json.Marshal(response)
	if err != nil {
		log.Printf("[WARN] normalizeArticleResponse: failed to re-marshal response for id=%s: %v", articleID, err)
		return data
	}
	return out
}

// extractDomain returns the canonical production domain from the request,
// checking X-Forwarded-Host, Referer, Origin, then Host in that order.
func extractDomain(req *http.Request) string {
	var raw string

	if forwardedHost := req.Header.Get("X-Forwarded-Host"); forwardedHost != "" {
		raw = cleanDomain(forwardedHost)
		log.Printf("[DEBUG] Domain from X-Forwarded-Host: %s", raw)
	} else if referer := req.Header.Get("Referer"); referer != "" {
		raw = extractDomainFromURL(referer)
		log.Printf("[DEBUG] Domain from Referer: %s", raw)
	} else if origin := req.Header.Get("Origin"); origin != "" {
		raw = extractDomainFromURL(origin)
		log.Printf("[DEBUG] Domain from Origin: %s", raw)
	} else if host := req.Host; host != "" {
		raw = cleanDomain(host)
		log.Printf("[DEBUG] Domain from Host: %s", raw)
	}

	if raw == "" {
		log.Printf("[DEBUG] No domain found in request")
		return ""
	}

	// Normalise UAT / www. variants → canonical production domain
	// e.g. "uat-bodytheory.imds.tv" → "bodytheory.com"
	//      "www.bodytheory.com"     → "bodytheory.com"
	production := middlewares.ResolveToProductionDomain(raw)
	if production != raw {
		log.Printf("[DEBUG] Domain normalised: %s → %s", raw, production)
	}
	return production
}

// extractDomainFromURL extracts the domain from a full URL
func extractDomainFromURL(urlStr string) string {
	// Remove protocol
	urlStr = strings.TrimPrefix(urlStr, "https://")
	urlStr = strings.TrimPrefix(urlStr, "http://")

	// Remove path
	if idx := strings.Index(urlStr, "/"); idx != -1 {
		urlStr = urlStr[:idx]
	}

	return cleanDomain(urlStr)
}

// cleanDomain removes port numbers and cleans up the domain
func cleanDomain(domain string) string {
	// Remove port if present
	if idx := strings.Index(domain, ":"); idx != -1 {
		domain = domain[:idx]
	}

	domain = strings.TrimSpace(domain)
	domain = strings.ToLower(domain)

	return domain
}

// domainCategories returns the value stored under domain in the CMS
// getcategories "data" map. Keys are compared after cleanDomain because some
// CMS keys carry stray spaces or capitals (" criticalrole.com").
func domainCategories(data map[string]interface{}, domain string) (interface{}, bool) {
	if categories, exists := data[domain]; exists {
		return categories, true
	}
	for key, categories := range data {
		if cleanDomain(key) == domain {
			return categories, true
		}
	}
	return nil, false
}

// filterCategoriesByDomain filters the categories response to only include
// the specified domain. Returns the filtered response in the same structure.
func filterCategoriesByDomain(response map[string]interface{}, domain string) map[string]interface{} {
	data, ok := response["data"].(map[string]interface{})
	if !ok {
		log.Printf("[WARN] Invalid category response structure")
		return response
	}

	// Check if the domain exists in the data
	if categories, exists := domainCategories(data, domain); exists {
		log.Printf("[INFO] Found categories for domain: %s", domain)
		// Return only the requested domain's categories
		return map[string]interface{}{
			"data": map[string]interface{}{
				domain: categories,
			},
		}
	}

	log.Printf("[WARN] No categories found for domain: %s, returning all categories", domain)
	// If domain not found, return all categories
	return response
}

// applySearchAndPagination applies search filtering and pagination to the articles response
func applySearchAndPagination(response map[string]interface{}, search, page, limit string) map[string]interface{} {
	data, ok := response["data"].([]interface{})
	if !ok {
		log.Printf("[WARN] Invalid articles response structure")
		return response
	}

	// Apply search filter if provided
	filteredData := data
	if search != "" {
		filteredData = filterArticlesBySearch(data, search)
		log.Printf("[INFO] Search filter applied: '%s', results: %d -> %d", search, len(data), len(filteredData))
	}

	totalCount := len(filteredData)

	// Apply pagination if parameters are provided
	pageNum := 1
	limitNum := 10 // default limit

	if page != "" {
		if p, err := strconv.Atoi(page); err == nil && p > 0 {
			pageNum = p
		}
	}

	if limit != "" {
		if l, err := strconv.Atoi(limit); err == nil && l > 0 {
			limitNum = l
		}
	}

	// Calculate pagination
	startIndex := (pageNum - 1) * limitNum
	endIndex := startIndex + limitNum

	if startIndex >= totalCount {
		// Page out of range, return empty results
		return map[string]interface{}{
			"data": []interface{}{},
			"pagination": map[string]interface{}{
				"page":        pageNum,
				"limit":       limitNum,
				"total":       totalCount,
				"total_pages": (totalCount + limitNum - 1) / limitNum,
				"has_next":    false,
				"has_prev":    pageNum > 1,
			},
		}
	}

	if endIndex > totalCount {
		endIndex = totalCount
	}

	paginatedData := filteredData[startIndex:endIndex]
	totalPages := (totalCount + limitNum - 1) / limitNum

	log.Printf("[INFO] Pagination applied: page=%d, limit=%d, total=%d, showing=%d",
		pageNum, limitNum, totalCount, len(paginatedData))

	return map[string]interface{}{
		"data": paginatedData,
		"pagination": map[string]interface{}{
			"page":        pageNum,
			"limit":       limitNum,
			"total":       totalCount,
			"total_pages": totalPages,
			"has_next":    pageNum < totalPages,
			"has_prev":    pageNum > 1,
		},
	}
}

// filterArticlesBySearch filters articles based on search query
// Searches in: title, sub_head, keywords, meta_title
func filterArticlesBySearch(articles []interface{}, search string) []interface{} {
	if search == "" {
		return articles
	}

	searchLower := strings.ToLower(strings.TrimSpace(search))
	if searchLower == "" {
		return articles
	}

	var filtered []interface{}
	for _, item := range articles {
		article, ok := item.(map[string]interface{})
		if !ok {
			continue
		}

		// Search in multiple fields
		title := strings.ToLower(getStringField(article, "title"))
		subHead := strings.ToLower(getStringField(article, "sub_head"))
		keywords := strings.ToLower(getStringField(article, "keywords"))
		metaTitle := strings.ToLower(getStringField(article, "meta_title"))

		if strings.Contains(title, searchLower) ||
			strings.Contains(subHead, searchLower) ||
			strings.Contains(keywords, searchLower) ||
			strings.Contains(metaTitle, searchLower) {
			filtered = append(filtered, item)
		}
	}

	return filtered
}

// getStringField safely gets a string field from a map
func getStringField(m map[string]interface{}, key string) string {
	if val, ok := m[key]; ok {
		if str, ok := val.(string); ok {
			return str
		}
	}
	return ""
}

// extractCategoryIDs pulls top-level category ID strings from a GetCategories
// response for the given domain.
//
// The CMS returns a structure like:
//
//	{"data": {"bodytheory.com": [{"cat_id":"1",...}, ...]}}
//
// Only top-level cat_id values are returned. Subcategory IDs must not be used
// with GetCategoryArticles(cat_id) — those IDs are not globally unique and are
// resolved as unrelated top-level categories on other sites. Parent category
// fetches already include nearly all subcategory articles; filtered subcategory
// lists must use GetSubcategoryArticles(cat_id, subcat_id) instead.
//
// If the domain key is not present the function tries every value in "data"
// that is a []interface{} (handles flat/non-domain-keyed responses).
// Common field names tried for the ID: cat_id, id, category_id, catId.
func extractCategoryIDs(response map[string]interface{}, domain string) []string {
	data, ok := response["data"].(map[string]interface{})
	if !ok {
		log.Printf("[WARN] extractCategoryIDs: unexpected categories structure (data is %T)", response["data"])
		return nil
	}

	var categories []interface{}

	// Prefer domain-keyed slice (most common CMS layout).
	if cats, exists := domainCategories(data, domain); exists {
		categories, _ = cats.([]interface{})
	}

	// Fall back: iterate values and use the first []interface{} found.
	if categories == nil {
		for _, v := range data {
			if cats, ok := v.([]interface{}); ok {
				categories = cats
				break
			}
		}
	}

	if len(categories) == 0 {
		return nil
	}

	seen := make(map[string]bool)
	var ids []string

	addID := func(id string) {
		if id != "" && !seen[id] {
			seen[id] = true
			ids = append(ids, id)
		}
	}

	for _, item := range categories {
		cat, ok := item.(map[string]interface{})
		if !ok {
			continue
		}
		// Collect the top-level category ID only.
		for _, field := range []string{"cat_id", "id", "category_id", "catId"} {
			if id := getStringField(cat, field); id != "" {
				addID(id)
				break
			}
		}
	}
	return ids
}

// fetchAllArticlesForDomain returns a deduplicated, merged flat slice of
// articles for a domain by:
//  1. Calling GetCategories() (cached) and extracting category IDs.
//  2. Calling GetCategoryArticles(catID) (cached) for each category.
//  3. Merging and deduplicating by article ID across all categories.
//
// If a single category fetch fails it is skipped with a warning so that
// partial results are still returned rather than a hard error.
func fetchAllArticlesForDomain(domain string) ([]interface{}, error) {
	catData, err := cmsService.GetCategories()
	if err != nil {
		return nil, fmt.Errorf("fetching categories for domain %s: %w", domain, err)
	}

	var catResponse map[string]interface{}
	if err := json.Unmarshal(catData, &catResponse); err != nil {
		return nil, fmt.Errorf("parsing categories for domain %s: %w", domain, err)
	}

	catIDs := extractCategoryIDs(catResponse, domain)
	if len(catIDs) == 0 {
		log.Printf("[WARN] fetchAllArticlesForDomain: no category IDs found for domain=%s", domain)
		return []interface{}{}, nil
	}
	log.Printf("[INFO] fetchAllArticlesForDomain: domain=%s found %d categories", domain, len(catIDs))

	seen := make(map[string]bool)
	merged := make([]interface{}, 0)

	for _, catID := range catIDs {
		artData, err := cmsService.GetCategoryArticles(catID)
		if err != nil {
			log.Printf("[WARN] fetchAllArticlesForDomain: skipping catId=%s: %v", catID, err)
			continue
		}

		var artResponse map[string]interface{}
		if err := json.Unmarshal(artData, &artResponse); err != nil {
			log.Printf("[WARN] fetchAllArticlesForDomain: skipping catId=%s (parse error): %v", catID, err)
			continue
		}

		articles, ok := artResponse["data"].([]interface{})
		if !ok {
			log.Printf("[WARN] fetchAllArticlesForDomain: unexpected articles structure for catId=%s", catID)
			continue
		}

		for _, item := range articles {
			article, ok := item.(map[string]interface{})
			if !ok {
				continue
			}
			normalizeImagesAttr(article)
			// Deduplicate: try common article ID field names.
			artID := getStringField(article, "id")
			if artID == "" {
				artID = getStringField(article, "article_id")
			}
			if artID != "" {
				if seen[artID] {
					continue
				}
				seen[artID] = true
			}
			merged = append(merged, item)
		}
		log.Printf("[INFO] fetchAllArticlesForDomain: catId=%s contributed %d articles", catID, len(articles))
	}

	log.Printf("[INFO] fetchAllArticlesForDomain: domain=%s total merged articles=%d", domain, len(merged))
	return merged, nil
}

// filterArticlesByKeyword filters articles whose title, sub_head, content,
// keywords, or meta_title contains the keyword (case-insensitive). sub_head is
// the excerpt/subtitle field returned by the CMS category-articles API and is
// the primary searchable text field alongside title. keywords matches live
// search, which returns articles tagged with the phrase.
func filterArticlesByKeyword(articles []interface{}, keyword string) []interface{} {
	kw := strings.ToLower(strings.TrimSpace(keyword))
	if kw == "" {
		return articles
	}

	filtered := make([]interface{}, 0, len(articles))
	for _, item := range articles {
		article, ok := item.(map[string]interface{})
		if !ok {
			continue
		}
		title := strings.ToLower(getStringField(article, "title"))
		subHead := strings.ToLower(getStringField(article, "sub_head"))
		content := strings.ToLower(getStringField(article, "content"))
		keywords := strings.ToLower(getStringField(article, "keywords"))
		metaTitle := strings.ToLower(getStringField(article, "meta_title"))
		if strings.Contains(title, kw) || strings.Contains(subHead, kw) || strings.Contains(content, kw) ||
			strings.Contains(keywords, kw) || strings.Contains(metaTitle, kw) {
			filtered = append(filtered, item)
		}
	}
	return filtered
}

// publishDateFormats are the date layouts tried when parsing article dates.
var publishDateFormats = []string{
	time.RFC3339,
	"2006-01-02 15:04:05",
	"2006-01-02",
}

// parsePublishDate attempts to parse a date string using known CMS formats.
func parsePublishDate(s string) (time.Time, bool) {
	for _, layout := range publishDateFormats {
		if t, err := time.Parse(layout, s); err == nil {
			return t, true
		}
	}
	return time.Time{}, false
}

// articleDate returns the best available date string for an article,
// trying publish_date first then falling back to timestamp.
func articleDate(a map[string]interface{}) string {
	if d := getStringField(a, "publish_date"); d != "" {
		return d
	}
	return getStringField(a, "timestamp")
}

// sortArticlesByRecent returns a copy of articles sorted by publish_date /
// timestamp descending (most recent first). Items whose date cannot be parsed
// fall to the end and preserve their original relative order.
func sortArticlesByRecent(articles []interface{}) []interface{} {
	sorted := make([]interface{}, len(articles))
	copy(sorted, articles)

	sort.SliceStable(sorted, func(i, j int) bool {
		ai, _ := sorted[i].(map[string]interface{})
		aj, _ := sorted[j].(map[string]interface{})

		dateI := articleDate(ai)
		dateJ := articleDate(aj)

		ti, okI := parsePublishDate(dateI)
		tj, okJ := parsePublishDate(dateJ)

		if okI && okJ {
			return ti.After(tj)
		}
		if okI {
			return true
		}
		if okJ {
			return false
		}
		// Both unparseable: fall back to lexicographic descending
		return dateI > dateJ
	})

	return sorted
}

// sortArticlesByID returns a copy of articles ordered by numeric article ID,
// highest (newest) first — the homepage order of the legacy theme2 sites.
// Articles without a numeric ID go last, keeping their relative order.
func sortArticlesByID(articles []interface{}) []interface{} {
	// Each ID is parsed once, not on every comparison.
	type keyedArticle struct {
		item interface{}
		id   int64
		ok   bool
	}
	keyed := make([]keyedArticle, len(articles))
	for i, item := range articles {
		m, _ := item.(map[string]interface{})
		id, err := strconv.ParseInt(firstNonEmptyField(m, "id", "article_id"), 10, 64)
		keyed[i] = keyedArticle{item: item, id: id, ok: err == nil}
	}
	sort.SliceStable(keyed, func(i, j int) bool {
		if keyed[i].ok && keyed[j].ok {
			return keyed[i].id > keyed[j].id
		}
		return keyed[i].ok && !keyed[j].ok
	})

	sorted := make([]interface{}, len(keyed))
	for i, k := range keyed {
		sorted[i] = k.item
	}
	return sorted
}

// paginateArticles slices a flat article list and wraps it with a pagination
// envelope matching the structure used by applySearchAndPagination.
func paginateArticles(articles []interface{}, page, limit string) map[string]interface{} {
	pageNum := 1
	limitNum := 10

	if page != "" {
		if p, err := strconv.Atoi(page); err == nil && p > 0 {
			pageNum = p
		}
	}
	if limit != "" {
		if l, err := strconv.Atoi(limit); err == nil && l > 0 {
			limitNum = l
		}
	}

	total := len(articles)
	startIndex := (pageNum - 1) * limitNum
	endIndex := startIndex + limitNum

	var pageData []interface{}
	if startIndex >= total {
		pageData = []interface{}{}
	} else {
		if endIndex > total {
			endIndex = total
		}
		pageData = articles[startIndex:endIndex]
	}

	totalPages := 0
	if total > 0 {
		totalPages = (total + limitNum - 1) / limitNum
	}

	log.Printf("[INFO] paginateArticles: page=%d limit=%d total=%d showing=%d",
		pageNum, limitNum, total, len(pageData))

	return map[string]interface{}{
		"data": pageData,
		"pagination": map[string]interface{}{
			"page":        pageNum,
			"limit":       limitNum,
			"total":       total,
			"total_pages": totalPages,
			"has_next":    pageNum < totalPages,
			"has_prev":    pageNum > 1,
		},
	}
}
