package routes

import (
	"encoding/json"
	"fmt"
	"html/template"
	"log"
	"math"
	"net/url"
	"regexp"
	"sort"
	"strings"
	"unicode"

	"bitbucket.org/imediabrands/oos-service/middlewares"
)

// uiOverrideKeys are the blocks of a client config that are passed to the
// frontend verbatim and merged over its bundled config. Everything that
// shapes a site's look and content lives under these keys, so a new site can
// be defined from its client_configs/<client>.json alone:
//
//	template  - name of the frontend template that renders the site (e.g. "editorial")
//	shared    - header, navigation, footer, labels, rails
//	pages     - per-page components and content (homepage, articleDetails, ...)
//	directory - directory sites: default location, page size, categories, seo
var uiOverrideKeys = []string{"template", "shared", "pages", "directory"}

var (
	cssVarName  = regexp.MustCompile(`^--[a-zA-Z0-9_-]+$`)
	cssVarValue = regexp.MustCompile(`^[a-zA-Z0-9#%.,()'"\s_-]+$`)
)

// applyClientUI adds the client's UI blocks to the frontend override config
// and renders its theme as CSS variables. Call it once vars.OverrideConfig is set.
func applyClientUI(vars *templateVars, config *middlewares.ClientConfig) {
	if vars == nil || config == nil {
		return
	}
	vars.HeadbidAffId = sanitizeHeadbidAffID(config.GetString("headbid_aff_id"))
	vars.GoogleAdsenseAccount = sanitizeAdsenseAccount(config.GetString("google_adsense_account"))
	if config.Raw == nil {
		return
	}
	vars.OverrideConfig = mergeUIOverrides(vars.OverrideConfig, config.Raw)
	vars.ThemeCSS = themeCSS(config.Raw["theme"])
	vars.Stylesheets = sharedStylesheets(config.Raw["shared"])
}

// navLink is a top-level shared.navigation.staticItems entry: its label and
// its position in the menu.
type navLink struct {
	Label string
	Index int
}

// navLinksByPath maps each top-level navigation URL ("/places-to-go") of a raw
// client config to its label and menu position. Legacy sites name and order
// their categories in the menu as live does; the CMS names can differ in case
// ("Places to Go") and come in another order.
func navLinksByPath(raw map[string]interface{}) map[string]navLink {
	shared, _ := raw["shared"].(map[string]interface{})
	navigation, _ := shared["navigation"].(map[string]interface{})
	items, _ := navigation["staticItems"].([]interface{})
	links := make(map[string]navLink, len(items))
	for i, entry := range items {
		item, _ := entry.(map[string]interface{})
		label, _ := item["label"].(string)
		path, _ := item["url"].(string)
		if label == "" || path == "" {
			continue
		}
		if _, seen := links[path]; !seen {
			links[path] = navLink{Label: label, Index: i}
		}
	}
	return links
}

// categoryLabel returns the menu's label for the category at /{slug}, or
// fallback (the CMS name) when the menu doesn't link to it.
func categoryLabel(config *middlewares.ClientConfig, slug, fallback string) string {
	if config == nil || slug == "" {
		return fallback
	}
	if link, ok := navLinksByPath(config.Raw)["/"+slug]; ok {
		return link.Label
	}
	return fallback
}

// menuLinksTo reports whether the site's menu has a top-level link to path.
func menuLinksTo(config *middlewares.ClientConfig, path string) bool {
	_, ok := navLinksByPath(config.Raw)[path]
	return ok
}

// sortCategoriesByNav orders categories as the site's menu does; categories
// the menu doesn't link to follow in their CMS order.
func sortCategoriesByNav(config *middlewares.ClientConfig, categories []sitemapCategory) {
	if config == nil {
		return
	}
	links := navLinksByPath(config.Raw)
	position := func(c sitemapCategory) int {
		if link, ok := links["/"+c.Slug]; ok {
			return link.Index
		}
		return math.MaxInt
	}
	sort.SliceStable(categories, func(i, j int) bool { return position(categories[i]) < position(categories[j]) })
}

// searchKeywordTitle returns the search page's <title> for keyword from
// shared.labels.searchTitle (e.g. "Search | {keyword}"), or "" when the site
// sets none or there is no keyword. The editorial template uses the same label.
func searchKeywordTitle(config *middlewares.ClientConfig, keyword string) string {
	keyword = strings.TrimSpace(keyword)
	if config == nil || keyword == "" {
		return ""
	}
	shared, _ := config.Raw["shared"].(map[string]interface{})
	labels, _ := shared["labels"].(map[string]interface{})
	pattern, _ := labels["searchTitle"].(string)
	if pattern == "" {
		return ""
	}
	return strings.Replace(pattern, "{keyword}", ucwords(keyword), 1)
}

// ucwords upper-cases the first letter of each space-separated word, like
// oos-singlecube's ucwords (the rest of each word is kept as typed).
func ucwords(value string) string {
	runes := []rune(value)
	for i, r := range runes {
		if i == 0 || unicode.IsSpace(runes[i-1]) {
			runes[i] = unicode.ToUpper(r)
		}
	}
	return string(runes)
}

// sharedStylesheets returns the https stylesheet URLs (e.g. web fonts) listed
// in shared.stylesheets, so the page links them in <head> before first paint
// instead of after React loads. Entries that aren't absolute https URLs (or
// protocol-relative "//host/...") or that contain whitespace are skipped.
// Kept verbatim: the frontend's useStylesheets skips a stylesheet whose href
// is already in the page.
func sharedStylesheets(shared interface{}) []string {
	block, ok := shared.(map[string]interface{})
	if !ok {
		return nil
	}
	list, ok := block["stylesheets"].([]interface{})
	if !ok {
		return nil
	}
	var out []string
	for _, entry := range list {
		href, ok := entry.(string)
		href = strings.TrimSpace(href)
		if !ok || href == "" {
			continue
		}
		// Whitespace inside a URL is dropped by browsers' URL parsing, so an
		// entry that has any is rejected rather than silently rewritten
		// (same rule as oos-singlecube's safeHttpsUrl).
		if strings.ContainsAny(href, " \t\r\n") {
			log.Printf("[WARN] ui overrides: ignoring stylesheet %q", href)
			continue
		}
		absolute := href
		if strings.HasPrefix(href, "//") {
			absolute = "https:" + href
		}
		u, err := url.Parse(absolute)
		if err != nil || u.Scheme != "https" || u.Host == "" {
			log.Printf("[WARN] ui overrides: ignoring stylesheet %q", href)
			continue
		}
		out = append(out, href)
	}
	return out
}

// mergeUIOverrides copies the UI blocks of raw into the JSON object in
// existing. raw keeps its original key case (unlike viper), which the
// frontend relies on (e.g. staticItems, useApiCategories).
func mergeUIOverrides(existing template.JS, raw map[string]interface{}) template.JS {
	merged := map[string]interface{}{}
	if err := json.Unmarshal([]byte(existing), &merged); err != nil {
		log.Printf("[WARN] ui overrides: could not parse override config: %v", err)
		return existing
	}
	for _, key := range uiOverrideKeys {
		if v, ok := raw[key]; ok {
			merged[key] = v
		}
	}
	out, err := json.Marshal(merged)
	if err != nil {
		log.Printf("[WARN] ui overrides: could not encode override config: %v", err)
		return existing
	}
	return template.JS(out)
}

// themeCSS turns a client config "theme" object ({"--color-bg": "#fff", ...})
// into CSS custom property declarations. Only custom properties with plain
// values are emitted; anything else is skipped so config can't inject CSS.
func themeCSS(v interface{}) template.CSS {
	theme, ok := v.(map[string]interface{})
	if !ok {
		return ""
	}
	names := make([]string, 0, len(theme))
	for name := range theme {
		names = append(names, name)
	}
	sort.Strings(names)

	var b strings.Builder
	for _, name := range names {
		value, ok := theme[name].(string)
		value = strings.TrimSpace(value)
		if !ok || !cssVarName.MatchString(name) || !cssVarValue.MatchString(value) ||
			strings.Contains(strings.ToLower(value), "url(") {
			log.Printf("[WARN] ui overrides: ignoring theme entry %q", name)
			continue
		}
		fmt.Fprintf(&b, "%s:%s;", name, value)
	}
	return template.CSS(b.String())
}

// headbidAffIDRe allows only numeric Headbid affiliate IDs, one or several
// joined by "_" as live sends them ("16678_127594_127595"), so it is safe to
// interpolate into the monitor script URL of the shared HTML template.
var headbidAffIDRe = regexp.MustCompile(`^[0-9]{1,12}(_[0-9]{1,12}){0,15}$`)

// sanitizeHeadbidAffID returns the headbid_aff_id config value if it is a plain
// number (or "_"-joined numbers), else "" (no monitor script is rendered).
func sanitizeHeadbidAffID(id string) string {
	id = strings.TrimSpace(id)
	if !headbidAffIDRe.MatchString(id) {
		return ""
	}
	return id
}

// adsenseAccountRe allows a google-adsense-account value ("sites-2288675768043065", "ca-pub-123").
var adsenseAccountRe = regexp.MustCompile(`^[a-z]+(-[a-z]+)*-[0-9]{1,24}$`)

// sanitizeAdsenseAccount returns the google_adsense_account config value when
// it looks like one, else "" (no meta is rendered).
func sanitizeAdsenseAccount(account string) string {
	account = strings.TrimSpace(account)
	if !adsenseAccountRe.MatchString(account) {
		return ""
	}
	return account
}
