package routes

import (
	"encoding/json"
	"log"
	"time"

	"bitbucket.org/imediabrands/oos-service/middlewares"
	"github.com/spf13/viper"
)

const (
	// cmsWarmWorkers caps concurrent CMS requests per warm step, so warming
	// doesn't crowd out the requests of real visitors.
	cmsWarmWorkers = 4
	// cmsWarmArticlesPerSite is how many of a site's newest articles get warmed:
	// the ones its homepage and category pages lead with. The rest load on demand.
	cmsWarmArticlesPerSite = 24
	// cmsWarmRetryDelay is the wait before the next pass when a pass couldn't
	// start. Only the categories request has run by then, so retrying costs little.
	cmsWarmRetryDelay = time.Minute
)

// StartCMSWarmer keeps the CMS cache full in the background when "cms_warm" is
// set, so the first visitor after a restart or a cache expiry doesn't wait for
// the CMS. A pass runs at startup, then every half cache TTL so entries are
// replaced before they expire, or after cmsWarmRetryDelay if it couldn't start.
// Must run after ClientConfigMiddleware has loaded the site list.
func StartCMSWarmer() {
	if !viper.GetBool("cms_warm") {
		return
	}
	interval := time.Duration(cmsCacheMaxAge) * time.Second / 2
	go func() {
		for {
			delay := interval
			if !warmCMSCache(middlewares.ProductionDomains()) {
				delay = cmsWarmRetryDelay
			}
			time.Sleep(delay)
		}
	}()
}

// logWarmPanic is deferred around warmer work that runs outside net/http's
// per-request recovery, so odd CMS content can't take the whole service down.
func logWarmPanic(what string) {
	if r := recover(); r != nil {
		log.Printf("[ERROR] warmCMSCache: %s: panic: %v", what, r)
	}
}

// warmCMSCache refreshes the categories, every category's article list and each
// site's newest articles for the given domains. Domains the CMS doesn't have are
// skipped. A failed request is logged and leaves that cache entry as it was.
// Returns false if the pass couldn't get past the categories, including on a panic.
func warmCMSCache(domains []string) (ok bool) {
	defer logWarmPanic("pass")
	start := time.Now()

	catData, err := cmsService.RefreshCategories()
	if err != nil {
		log.Printf("[WARN] warmCMSCache: categories: %v", err)
		return false
	}
	var categories map[string]interface{}
	if err := json.Unmarshal(catData, &categories); err != nil {
		log.Printf("[WARN] warmCMSCache: parsing categories: %v", err)
		return false
	}
	cmsDomains, _ := categories["data"].(map[string]interface{})

	var catIDs []string
	sites := make([]string, 0, len(domains))
	for _, domain := range domains {
		if _, exists := domainCategories(cmsDomains, domain); exists {
			sites = append(sites, domain)
			catIDs = append(catIDs, extractCategoryIDs(categories, domain)...)
		}
	}

	forEachConcurrently(catIDs, cmsWarmWorkers, func(catID string) {
		defer logWarmPanic("catId=" + catID)
		if _, err := cmsService.RefreshCategoryArticles(catID); err != nil {
			log.Printf("[WARN] warmCMSCache: catId=%s: %v", catID, err)
		}
	})
	log.Printf("[INFO] warmCMSCache: %d sites, %d categories warm after %v", len(sites), len(catIDs), time.Since(start))

	// Articles come after every site's listings, so listings are ready as early as possible.
	articlesWarmed := 0
	for _, domain := range sites {
		ids := newestArticleIDs(domain, cmsWarmArticlesPerSite)
		articlesWarmed += len(ids)
		forEachConcurrently(ids, cmsWarmWorkers, func(id string) {
			defer logWarmPanic("article id=" + id)
			data, err := cmsService.RefreshArticle(id)
			if err != nil {
				log.Printf("[WARN] warmCMSCache: article id=%s: %v", id, err)
				return
			}
			// Loads the articles this one links to, which DataArticleHandler needs too.
			// The rewritten links are discarded, so the URL shape doesn't matter here.
			normalizeArticleResponse(id, data, domain, articleURLOptions{WithSubcategory: true})
		})
	}
	log.Printf("[INFO] warmCMSCache: done, %d articles warmed, took %v", articlesWarmed, time.Since(start))
	return true
}

// newestArticleIDs returns up to limit article IDs for a domain, newest first.
func newestArticleIDs(domain string, limit int) []string {
	defer logWarmPanic("articles of " + domain)
	articles, err := fetchAllArticlesForDomain(domain)
	if err != nil {
		log.Printf("[WARN] warmCMSCache: articles of %s: %v", domain, err)
		return nil
	}
	ids := make([]string, 0, limit)
	for _, item := range sortArticlesByID(articles) {
		if len(ids) == limit {
			break
		}
		if article, ok := item.(map[string]interface{}); ok {
			if id := firstNonEmptyField(article, "id", "article_id"); isNumericID(id) {
				ids = append(ids, id)
			}
		}
	}
	return ids
}
