package routes

import (
	"bytes"
	"encoding/json"
	"encoding/xml"
	"fmt"
	"log"
	"net/http"
	"regexp"
	"slices"
	"strconv"
	"strings"
	"sync/atomic"
	"time"

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

const sitemapNS = "http://www.sitemaps.org/schemas/sitemap/0.9"

// xmlSitemapIndex is the root element for /sitemap.xml.
type xmlSitemapIndex struct {
	XMLName  xml.Name        `xml:"sitemapindex"`
	Xmlns    string          `xml:"xmlns,attr"`
	Sitemaps []xmlSitemapRef `xml:"sitemap"`
}

type xmlSitemapRef struct {
	Loc     string `xml:"loc"`
	LastMod string `xml:"lastmod"`
}

// xmlURLSet is the root element for urlset sitemaps.
type xmlURLSet struct {
	XMLName xml.Name `xml:"urlset"`
	Xmlns   string   `xml:"xmlns,attr"`
	URLs    []xmlURL `xml:"url"`
}

type xmlURL struct {
	Loc     string `xml:"loc"`
	LastMod string `xml:"lastmod"`
}

type sitemapCategory struct {
	ID            string
	Name          string
	Slug          string
	Subcategories []sitemapSubcategory
}

type sitemapSubcategory struct {
	ID   string
	Name string
	Slug string
}

var sitemapCategoryPathRe = regexp.MustCompile(`(?i)^/sitemap_([a-z0-9]+(?:-[a-z0-9]+)*)\.xml$`)

// legacySitemapPathRe matches the legacy sites' child sitemap URLs,
// /sitemap/sitemap_{slug}.xml, for plain lowercase slugs only (see
// slugSegmentRe), so junk never redirects.
var legacySitemapPathRe = regexp.MustCompile(`^/sitemap/sitemap_([a-z0-9]+(?:-[a-z0-9]+)*)\.xml$`)

// defaultSitemapPages are the static pages /sitemap_pages.xml lists when the
// client config doesn't set "sitemapPages".
var defaultSitemapPages = []string{"/", "/about", "/contact", "/privacy", "/terms", "/sitemap"}

// sitemapPagePaths are the static page routes a client's "sitemapPages" may
// list, so config can't put arbitrary URLs in the sitemap.
var sitemapPagePaths = map[string]bool{
	"/": true, "/about": true, "/aboutus": true, "/contact": true, "/contactus": true,
	"/privacy": true, "/privacypolicy": true, "/terms": true, "/sitemap": true,
	"/for_advertisers": true,
}

// directorySitemapPagePaths are the pages a directory site's "sitemapPages"
// may list besides sitemapPagePaths.
var directorySitemapPagePaths = map[string]bool{"/categories": true, "/states": true}

// SitemapIndexHandler serves /sitemap.xml — an index of pages + per-category sitemaps.
func SitemapIndexHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		base := requestPublicBaseURL(req)
		cmsDomain := extractDomain(req)
		today := time.Now().UTC().Format("2006-01-02")

		refs := []xmlSitemapRef{
			{Loc: base + "/sitemap_pages.xml", LastMod: today},
		}

		config := middlewares.GetClientConfig(req.Context())
		categories, err := loadSitemapCategories(cmsDomain)
		if err != nil {
			log.Printf("[ERROR] SitemapIndexHandler: categories: %v", err)
			http.Error(w, "Failed to build sitemap", http.StatusInternalServerError)
			return
		}
		categories = categoryPathsFromConfig(config).withPaths(categories)
		if cmsUnlistedShopSite(req) {
			categories = nil // not the first CMS site's
		}
		sortCategoriesByNav(config, categories)
		for _, cat := range categories {
			refs = append(refs, xmlSitemapRef{
				Loc:     fmt.Sprintf("%s/sitemap_%s.xml", base, cat.Slug),
				LastMod: today,
			})
		}

		writeSitemapXML(w, xmlSitemapIndex{
			Xmlns:    sitemapNS,
			Sitemaps: refs,
		})
	})
}

// SitemapPagesHandler serves /sitemap_pages.xml with static site pages.
func SitemapPagesHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		base := requestPublicBaseURL(req)
		today := time.Now().UTC().Format("2006-01-02")

		config := middlewares.GetClientConfig(req.Context())
		paths := sitemapPagesFromConfig(config)
		if isShopSite(config) {
			paths = append(paths, shopSitemapListingPaths(req.Context())...)
		}

		urls := make([]xmlURL, 0, len(paths))
		for _, p := range paths {
			loc := base
			if p != "/" {
				loc = base + p
			}
			urls = append(urls, xmlURL{Loc: loc, LastMod: today})
		}

		writeSitemapXML(w, xmlURLSet{
			Xmlns: sitemapNS,
			URLs:  urls,
		})
	})
}

// sitemapPagesFromConfig returns the static page paths for
// /sitemap_pages.xml: the client config's "sitemapPages" list (e.g.
// ["/", "/about", "/privacy", "/terms"]) in its order, or defaultSitemapPages
// when unset. Paths that aren't static page routes or the site's own extra
// pages (see extraPageAt) are skipped; directory sites may also list
// /categories and /states. /sitemap, /for_advertisers for a site with that
// page, and a shop site's own pages (/deals, /top-brands, /categories when
// it has them) are always added.
func sitemapPagesFromConfig(config *middlewares.ClientConfig) []string {
	if config == nil || config.ViperConfig == nil || !config.ViperConfig.IsSet("sitemapPages") {
		if shopPaths := shopEnabledPagePaths(config); len(shopPaths) > 0 || !shopHasSitemapPage(config) {
			paths := slices.DeleteFunc(slices.Clone(defaultSitemapPages), func(p string) bool { return p == "/sitemap" && !shopHasSitemapPage(config) })
			return append(paths, shopPaths...)
		}
		return defaultSitemapPages
	}
	var paths []string
	for _, p := range config.ViperConfig.GetStringSlice("sitemapPages") {
		p = strings.TrimSpace(p)
		if p == "/sitemap" && !shopHasSitemapPage(config) {
			continue // a shop site without the page
		}
		if !sitemapPagePaths[p] && extraPageAt(config.Raw, p) == "" && !(directorySitemapPagePaths[p] && isDirectorySite(config)) &&
			!slices.Contains(shopEnabledPagePaths(config), p) {
			log.Printf("[WARN] sitemapPages: ignoring %q (not a static page route)", p)
			continue
		}
		paths = append(paths, p)
	}
	// The HTML sitemap, the advertisers page and a shop site's own pages belong
	// in the sitemap of every site that has them, whatever its own list says.
	for _, extra := range append([]string{"/sitemap", "/for_advertisers"}, shopEnabledPagePaths(config)...) {
		if slices.Contains(paths, extra) || (extra == "/for_advertisers" && !config.ViperConfig.IsSet("pages.forAdvertisers")) ||
			(extra == "/sitemap" && !shopHasSitemapPage(config)) {
			continue
		}
		paths = append(paths, extra)
	}
	return paths
}

// SitemapCategoryHandler serves /sitemap_{category}.xml with the category URL
// and all indexable articles in that category.
func SitemapCategoryHandler(categorySlug string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		slug := strings.ToLower(strings.TrimSpace(categorySlug))
		if slug == "" || slug == "pages" {
			http.NotFound(w, req)
			return
		}

		base := requestPublicBaseURL(req)
		cmsDomain := extractDomain(req)
		config := middlewares.GetClientConfig(req.Context())
		urlOpts := articleURLOptionsFromConfig(config)

		categories, err := loadSitemapCategories(cmsDomain)
		if err != nil {
			log.Printf("[ERROR] SitemapCategoryHandler: categories: %v", err)
			http.Error(w, "Failed to build sitemap", http.StatusInternalServerError)
			return
		}
		categories = urlOpts.CategoryPaths.withPaths(categories)
		if cmsUnlistedShopSite(req) {
			categories = nil // not the first CMS site's
		}

		var matched *sitemapCategory
		for i := range categories {
			if categories[i].Slug == slug {
				matched = &categories[i]
				break
			}
		}
		if matched == nil {
			http.NotFound(w, req)
			return
		}

		articles, err := loadCategoryArticles(matched.ID)
		if err != nil {
			log.Printf("[ERROR] SitemapCategoryHandler: articles catId=%s: %v", matched.ID, err)
			http.Error(w, "Failed to build sitemap", http.StatusInternalServerError)
			return
		}

		urls := make([]xmlURL, 0, len(articles)+1+len(matched.Subcategories))
		categoryLastMod := time.Now().UTC().Format("2006-01-02")
		urls = append(urls, xmlURL{
			Loc:     base + "/" + matched.Slug,
			LastMod: categoryLastMod,
		})
		for _, sub := range matched.Subcategories {
			urls = append(urls, xmlURL{
				Loc:     base + "/" + matched.Slug + "/" + sub.Slug,
				LastMod: categoryLastMod,
			})
		}

		// A category whose page shows its article (see categoryShowsArticle)
		// lists only that page, dated by its newest article.
		articlePage := categoryShowsArticle(config, matched.Slug)
		latest := time.Time{}
		for _, item := range articles {
			article, ok := item.(map[string]interface{})
			if !ok {
				continue
			}
			if !isIndexable(article) {
				continue
			}
			path := buildSitemapArticlePath(article, matched.Name, urlOpts)
			if path == "" {
				continue
			}
			lastMod := articleLastModDate(article)
			if t, err := time.Parse("2006-01-02", lastMod); err == nil && t.After(latest) {
				latest = t
				urls[0].LastMod = lastMod
			}
			if articlePage {
				continue
			}
			urls = append(urls, xmlURL{
				Loc:     base + path,
				LastMod: lastMod,
			})
		}

		writeSitemapXML(w, xmlURLSet{
			Xmlns: sitemapNS,
			URLs:  urls,
		})
	})
}

// tryServeSitemapXML handles /sitemap_*.xml paths that are not registered as
// literal routes (category sitemaps). Returns true when the request was handled.
func tryServeSitemapXML(w http.ResponseWriter, req *http.Request) bool {
	if req.Method != http.MethodGet {
		return false
	}
	m := sitemapCategoryPathRe.FindStringSubmatch(req.URL.Path)
	if m == nil {
		return false
	}
	slug := m[1]
	if strings.EqualFold(slug, "pages") {
		return false
	}
	SitemapCategoryHandler(slug).ServeHTTP(w, req)
	return true
}

// legacySitemapRedirectPath returns the sitemap path a legacy child sitemap
// URL redirects to, e.g. /sitemap/sitemap_claims-and-coverage.xml →
// /sitemap_claims-and-coverage.xml. Anything else is left alone so it 404s.
func legacySitemapRedirectPath(path string) (string, bool) {
	m := legacySitemapPathRe.FindStringSubmatch(path)
	if m == nil {
		return "", false
	}
	return "/sitemap_" + m[1] + ".xml", true
}

// serveLegacySitemapRedirect 301s a legacy /sitemap/sitemap_{slug}.xml URL to
// /sitemap_{slug}.xml. Reports whether it wrote a redirect.
func serveLegacySitemapRedirect(w http.ResponseWriter, req *http.Request) bool {
	target, ok := legacySitemapRedirectPath(req.URL.Path)
	if !ok {
		return false
	}
	redirectPermanently(w, req, target, req.URL.RawQuery)
	return true
}

func writeSitemapXML(w http.ResponseWriter, v interface{}) {
	w.Header().Set("Content-Type", "application/xml; charset=utf-8")
	w.Header().Set("X-Content-Type-Options", "nosniff")
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte(xml.Header))
	enc := xml.NewEncoder(w)
	enc.Indent("", "  ")
	if err := enc.Encode(v); err != nil {
		log.Printf("[ERROR] writeSitemapXML: %v", err)
	}
}

// requestPublicBaseURL, canonicalURL, isSitemapIndexableHost, and slugify
// live in seo.go alongside the rest of the SEO helpers.

func loadSitemapCategories(cmsDomain string) ([]sitemapCategory, error) {
	response, err := loadCMSCategories()
	if err != nil {
		return nil, err
	}
	return extractSitemapCategories(response, cmsDomain), nil
}

// parsedCMSCategories is a getcategories response with the bytes it was parsed from.
type parsedCMSCategories struct {
	raw      []byte
	response map[string]interface{}
}

// lastCMSCategories keeps the latest parse: every category page reads the list.
var lastCMSCategories atomic.Pointer[parsedCMSCategories]

// loadCMSCategories returns the parsed CMS categories of all sites, parsing
// again only when the CMS cache has new bytes. Callers share the result and
// must not modify it.
func loadCMSCategories() (map[string]interface{}, error) {
	if cmsService == nil {
		return nil, fmt.Errorf("cms service not initialized")
	}
	raw, err := cmsService.GetCategories()
	if err != nil {
		return nil, err
	}
	if last := lastCMSCategories.Load(); last != nil && bytes.Equal(last.raw, raw) {
		return last.response, nil
	}
	var response map[string]interface{}
	if err := json.Unmarshal(raw, &response); err != nil {
		return nil, err
	}
	lastCMSCategories.Store(&parsedCMSCategories{raw: raw, response: response})
	return response, nil
}

func loadCategoryArticles(catID string) ([]interface{}, error) {
	if cmsService == nil {
		return nil, fmt.Errorf("cms service not initialized")
	}
	raw, err := cmsService.GetCategoryArticles(catID)
	if err != nil {
		return nil, err
	}
	var response map[string]interface{}
	if err := json.Unmarshal(raw, &response); err != nil {
		return nil, err
	}
	articles, _ := response["data"].([]interface{})
	return articles, nil
}

func extractSitemapCategories(response map[string]interface{}, domain string) []sitemapCategory {
	data, ok := response["data"].(map[string]interface{})
	if !ok {
		return nil
	}

	var categories []interface{}
	if cats, exists := domainCategories(data, domain); exists {
		categories, _ = cats.([]interface{})
	}
	if categories == nil {
		for _, v := range data {
			if cats, ok := v.([]interface{}); ok {
				categories = cats
				break
			}
		}
	}

	out := make([]sitemapCategory, 0, len(categories))
	seen := make(map[string]bool)
	for _, item := range categories {
		cat, ok := item.(map[string]interface{})
		if !ok {
			continue
		}
		id := firstNonEmptyField(cat, "cat_id", "id", "category_id", "catId")
		name := firstNonEmptyField(cat, "cat_name", "name", "category_name", "title")
		if id == "" || name == "" {
			continue
		}
		slug := slugify(name)
		if slug == "" || seen[slug] {
			continue
		}
		seen[slug] = true
		out = append(out, sitemapCategory{
			ID:            id,
			Name:          name,
			Slug:          slug,
			Subcategories: extractSitemapSubcategories(cat),
		})
	}
	return out
}

// extractSitemapSubcategories parses the "subcategories" array nested under
// a category in the CMS getcategories response.
func extractSitemapSubcategories(cat map[string]interface{}) []sitemapSubcategory {
	rawSubs, _ := cat["subcategories"].([]interface{})
	if len(rawSubs) == 0 {
		return nil
	}

	out := make([]sitemapSubcategory, 0, len(rawSubs))
	seen := make(map[string]bool)
	for _, item := range rawSubs {
		sub, ok := item.(map[string]interface{})
		if !ok {
			continue
		}
		id := firstNonEmptyField(sub, "id", "sub_cat_id", "subcatId")
		name := firstNonEmptyField(sub, "name", "sub_cat_name")
		if id == "" || name == "" {
			continue
		}
		slug := slugify(name)
		if slug == "" || seen[slug] {
			continue
		}
		seen[slug] = true
		out = append(out, sitemapSubcategory{ID: id, Name: name, Slug: slug})
	}
	return out
}

func firstNonEmptyField(m map[string]interface{}, keys ...string) string {
	for _, key := range keys {
		if v := fieldAsString(m, key); v != "" {
			return v
		}
	}
	return ""
}

// fieldAsString reads string or numeric JSON fields as a string.
func fieldAsString(m map[string]interface{}, key string) string {
	if m == nil {
		return ""
	}
	val, ok := m[key]
	if !ok || val == nil {
		return ""
	}
	switch x := val.(type) {
	case string:
		return strings.TrimSpace(x)
	case float64:
		// JSON numbers decode as float64; article/category IDs are integers.
		return strconv.FormatInt(int64(x), 10)
	case int:
		return strconv.Itoa(x)
	case int64:
		return strconv.FormatInt(x, 10)
	case json.Number:
		return x.String()
	default:
		return strings.TrimSpace(fmt.Sprint(x))
	}
}

func buildSitemapArticlePath(article map[string]interface{}, fallbackCategory string, opts articleURLOptions) string {
	id := firstNonEmptyField(article, "id", "article_id")
	if id == "" {
		return ""
	}
	titleForSlug := firstNonEmptyField(article, "slug_title", "meta_title", "title")
	if opts.TitleOnly {
		titleForSlug = firstNonEmptyField(article, "title", "slug_title", "meta_title")
		// Untrimmed, like the article page's own canonical: legacyArticleSlug turns
		// an edge space into a hyphen.
		if raw, _ := article["title"].(string); opts.LegacySlug && strings.TrimSpace(raw) != "" {
			titleForSlug = raw
		}
	} else if opts.SlugFromTitle {
		titleForSlug = firstNonEmptyField(article, "slug_title", "title")
	}
	titleForSlug = articleSlugSource(titleForSlug, opts)
	category := firstNonEmptyField(article, "category")
	if category == "" {
		category = fallbackCategory
	}
	category = opts.CategoryPaths.urlCategory(category)
	// Same builder as the canonical article redirect, so sitemap URLs never
	// 301 and never start with "//".
	subCategory := ""
	if opts.WithSubcategory {
		subCategory = firstNonEmptyField(article, "sub_category")
	}
	if opts.LegacySlug {
		return buildLegacyArticleDetailPath(category, subCategory, id, titleForSlug)
	}
	return buildArticleDetailPath(category, subCategory, id, titleForSlug)
}

func articleLastModDate(article map[string]interface{}) string {
	if pd := getStringField(article, "publish_date"); pd != "" {
		if t, ok := parsePublishDate(pd); ok {
			return t.UTC().Format("2006-01-02")
		}
	}
	if formatted := formatArticleTimestamp(article); formatted != "" {
		if t, err := time.Parse(time.RFC3339, formatted); err == nil {
			return t.UTC().Format("2006-01-02")
		}
	}
	return time.Now().UTC().Format("2006-01-02")
}
