package routes

import (
	"context"
	"encoding/json"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"os"
	"strconv"

	"bitbucket.org/imediabrands/oos-service/middlewares"
	"github.com/julienschmidt/httprouter"
)

type articleListProps struct {
	StartContentServiceOrigin string `json:"startContentServiceOrigin,omitempty"`
	LocationServiceOrigin     string `json:"locationServiceOrigin,omitempty"`
	PortalStaticOrigin        string `json:"portalStaticOrigin,omitempty"`
	Category                  string `json:"category,omitempty"`
	SiteId                    string `json:"siteId,omitempty"`
	TesseractClient           string `json:"tesseractClient,omitempty"`
	DisplayName               string `json:"displayName,omitempty"`
	GaId                      string `json:"gaId,omitempty"`
}

type categoryPageProps struct {
	StartContentServiceOrigin string `json:"startContentServiceOrigin,omitempty"`
	LocationServiceOrigin     string `json:"locationServiceOrigin,omitempty"`
	PortalStaticOrigin        string `json:"portalStaticOrigin,omitempty"`
	Category                  string `json:"category,omitempty"`
	CategoryID                string `json:"categoryId,omitempty"`
	SiteId                    string `json:"siteId,omitempty"`
	TesseractClient           string `json:"tesseractClient,omitempty"`
	DisplayName               string `json:"displayName,omitempty"`
	GaId                      string `json:"gaId,omitempty"`
}

// Note: templateVars is defined in homepage.go and shared across routes

// ArticleListHandler serves the articles listing page using the root template.
func ArticleListHandler() http.Handler {
	return articleListHandler(pageTemplates())
}

// articleListHandler is ArticleListHandler rendering with tpl.
func articleListHandler(tpl *template.Template) http.Handler {
	categoryHandler := articleByCategoryHandler(tpl)

	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		ctx := req.Context()
		config := middlewares.GetClientConfig(ctx)
		if config == nil {
			http.Error(w, "client config not found", http.StatusInternalServerError)
			return
		}

		// A site whose menu links to its own "articles" CMS category lists that
		// category here; a menu link to /articles without one (localpages'
		// "Blog") gets the all-articles list.
		if menuLinksTo(config, "/articles") && !categoryRouteMissing(req, "articles", "") {
			params := httprouter.Params{httprouter.Param{Key: "categorySlug", Value: "articles"}}
			categoryHandler.ServeHTTP(w, req.WithContext(context.WithValue(ctx, httprouter.ParamsKey, params)))
			return
		}

		displayName := config.GetString("displayName")
		siteId := config.GetString("siteId")
		ga := gaSettingsFromConfig(config)
		tesseractClient := config.GetString("tesseractClient")
		tesseractCdnUrl := config.GetString("tesseract_cdn_url")
		portalStaticCdnUrl := config.GetString("portal_static_cdn_url")
		scsUrl := config.GetString("scs_url")

		if tesseractCdnUrl == "" {
			tesseractCdnUrl = "/static/tesseract"
		}

		hostname, _ := os.Hostname()
		deviceType := "\"desktop\""
		environment := "\"" + config.GetString("environment") + "\""

		// Build props for SingleCube component
		props := articleListProps{
			StartContentServiceOrigin: scsUrl,
			PortalStaticOrigin:        portalStaticCdnUrl,
			SiteId:                    siteId,
			Category:                  "articles",
			TesseractClient:           tesseractClient,
			DisplayName:               displayName,
			GaId:                      ga.GaId,
		}
		propsJSON, _ := json.Marshal(props)

		// Build override config
		overrideConfig := map[string]interface{}{
			"siteId":             siteId,
			"displayName":        displayName,
			"seoMeta":            config.GetStringMap("seoMeta"),
			"logoUrl":            logoURLFromConfig(config),
			"articleTitleSuffix": articleTitleSuffixFromConfig(config),
		}
		configJSON, _ := json.Marshal(overrideConfig)

		pageTitle, metaDescription := pageMetaOverride(
			config,
			"articles",
			"Articles - "+displayName,
			"Browse all articles on "+displayName,
		)

		vars := &templateVars{
			PageTitle:              pageTitle,
			MetaDescription:        metaDescription,
			OgTitle:                pageTitle,
			OgDescription:          metaDescription,
			TwitterTitle:           pageTitle,
			TwitterDescription:     metaDescription,
			FaviconUrl:             faviconURLFromConfig(config),
			DNSPrefetch:            []string{tesseractCdnUrl, scsUrl, portalStaticCdnUrl},
			CanonicalUrl:           canonicalURL(req),
			TesseractCdnUrl:        tesseractCdnUrl,
			TesseractClient:        tesseractClient,
			SingleCubeComponent:    "\"singlecube.ArticleList\"",
			SingleCubeProps:        template.JS(string(propsJSON)),
			OverrideConfig:         template.JS(string(configJSON)),
			DeviceType:             deviceType,
			Environment:            environment,
			TsuahComment:           template.HTML(fmt.Sprintf("<!-- TSUAH: %s -->", hostname)),
			GaId:                   ga.GaId,
			GaGtm:                  ga.GaGtm,
			GaCx:                   ga.GaCx,
			GtmId:                  ga.GtmId,
			GoogleCsa:              ga.GoogleCsa,
			GoogleSiteVerification: googleSiteVerificationFromConfig(config),
		}
		applyMetaRobots(w, vars, req, metaRobotsIndexable)
		applyClientUI(vars, config)
		applyStructuredData(vars, config, req, []breadcrumbItem{
			homeBreadcrumbItem(req),
			{Name: "Articles", URL: absoluteURL(req, "/articles")},
		})

		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if err := tpl.ExecuteTemplate(w, "root", vars); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})
}

// SearchPageHandler serves the /search page HTML shell. The React app
// (oos-singlecube) handles the route client-side and calls GET /data/articles
// to fetch results based on the ?term= query parameter (the live sites' form).
// /search?keyword= and ?search= URLs 301 to the ?term= form.
func SearchPageHandler() http.Handler {
	tpl := pageTemplates()

	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if serveLegacySearchRedirect(w, req) {
			return
		}

		ctx := req.Context()
		config := middlewares.GetClientConfig(ctx)
		if config == nil {
			http.Error(w, "client config not found", http.StatusInternalServerError)
			return
		}

		displayName := config.GetString("displayName")
		siteId := config.GetString("siteId")
		ga := gaSettingsFromConfig(config)
		tesseractClient := config.GetString("tesseractClient")
		tesseractCdnUrl := config.GetString("tesseract_cdn_url")
		portalStaticCdnUrl := config.GetString("portal_static_cdn_url")
		scsUrl := config.GetString("scs_url")

		if tesseractCdnUrl == "" {
			tesseractCdnUrl = "/static/tesseract"
		}

		hostname, _ := os.Hostname()
		deviceType := "\"desktop\""
		environment := "\"" + config.GetString("environment") + "\""

		props := articleListProps{
			StartContentServiceOrigin: scsUrl,
			PortalStaticOrigin:        portalStaticCdnUrl,
			SiteId:                    siteId,
			Category:                  "search",
			TesseractClient:           tesseractClient,
			DisplayName:               displayName,
			GaId:                      ga.GaId,
		}
		propsJSON, _ := json.Marshal(props)

		overrideConfig := map[string]interface{}{
			"siteId":             siteId,
			"displayName":        displayName,
			"seoMeta":            config.GetStringMap("seoMeta"),
			"logoUrl":            logoURLFromConfig(config),
			"articleTitleSuffix": articleTitleSuffixFromConfig(config),
		}
		configJSON, _ := json.Marshal(overrideConfig)

		pageTitle, metaDescription := pageMetaOverride(config, "search", "Search - "+displayName, "Search articles on "+displayName)
		if title := searchKeywordTitle(config, req.URL.Query().Get("term")); title != "" {
			pageTitle = title
		}

		vars := &templateVars{
			PageTitle:              pageTitle,
			MetaDescription:        metaDescription,
			OgTitle:                pageTitle,
			OgDescription:          metaDescription,
			TwitterTitle:           pageTitle,
			TwitterDescription:     metaDescription,
			FaviconUrl:             faviconURLFromConfig(config),
			DNSPrefetch:            []string{tesseractCdnUrl, scsUrl, portalStaticCdnUrl},
			CanonicalUrl:           canonicalURL(req),
			TesseractCdnUrl:        tesseractCdnUrl,
			TesseractClient:        tesseractClient,
			SingleCubeComponent:    "\"singlecube.ArticleList\"",
			SingleCubeProps:        template.JS(string(propsJSON)),
			OverrideConfig:         template.JS(string(configJSON)),
			DeviceType:             deviceType,
			Environment:            environment,
			TsuahComment:           template.HTML(fmt.Sprintf("<!-- TSUAH: %s -->", hostname)),
			GaId:                   ga.GaId,
			GaGtm:                  ga.GaGtm,
			GaCx:                   ga.GaCx,
			GtmId:                  ga.GtmId,
			GoogleCsa:              ga.GoogleCsa,
			GoogleSiteVerification: googleSiteVerificationFromConfig(config),
		}
		applyMetaRobots(w, vars, req, metaRobotsSearch)
		applyClientUI(vars, config)
		applyStructuredData(vars, config, req, []breadcrumbItem{
			homeBreadcrumbItem(req),
			{Name: "Search", URL: absoluteURL(req, "/search")},
		})
		applyOgDefaults(vars, config)

		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if err := tpl.ExecuteTemplate(w, "root", vars); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})
}

// validSortValues is the set of accepted sort parameter values.
var validSortValues = map[string]bool{
	"recent": true,
	"id":     true,
}

// DataArticlesHandler serves a paginated, searchable, and sortable JSON list
// of articles scoped to the request domain (resolved from the Host /
// X-Forwarded-Host header, same as DataCategoriesHandler).
//
//	GET /data/articles?page=1&limit=20&sort=recent&q=climate&start=6
//
// Query parameters:
//   - page  – page number (default 1; invalid values fall back to 1)
//   - limit – page size   (default 10; invalid values fall back to 10)
//   - sort  – "recent" sorts by publish_date descending, "id" by article ID
//     descending (newest first); any other non-empty value returns 400
//   - q     – keyword searched against title and content (case-insensitive)
//   - start – zero-based offset applied after sort/filter; articles before
//     this index are skipped (default 0)
func DataArticlesHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		domain := extractDomain(req)
		log.Printf("[INFO] DataArticlesHandler: request domain: %s", domain)

		query := req.URL.Query()
		page := query.Get("page")
		limit := query.Get("limit")
		sortParam := query.Get("sort")
		q := query.Get("q")
		startParam := query.Get("start")

		log.Printf("[INFO] DataArticlesHandler: domain=%s page=%s limit=%s sort=%s q=%s start=%s",
			domain, page, limit, sortParam, q, startParam)

		if sortParam != "" && !validSortValues[sortParam] {
			http.Error(w, "invalid sort value: supported values are 'recent' and 'id'", http.StatusBadRequest)
			return
		}

		articles, err := fetchAllArticlesForDomain(domain)
		if err != nil {
			log.Printf("[ERROR] fetching articles (domain=%s): %v", domain, err)
			http.Error(w, "failed to fetch articles", http.StatusInternalServerError)
			return
		}
		// A shop site the CMS doesn't list has no articles, not the first site's.
		if cmsUnlistedShopSite(req) {
			articles = []interface{}{}
		}

		if q != "" {
			before := len(articles)
			articles = filterArticlesByKeyword(articles, q)
			log.Printf("[INFO] Keyword filter '%s': %d -> %d", q, before, len(articles))
		}

		switch sortParam {
		case "recent":
			articles = sortArticlesByRecent(articles)
		case "id":
			articles = sortArticlesByID(articles)
		}

		if startParam != "" {
			if s, err := strconv.Atoi(startParam); err == nil && s > 0 {
				if s >= len(articles) {
					articles = []interface{}{}
				} else {
					articles = articles[s:]
				}
				log.Printf("[INFO] DataArticlesHandler: start=%d applied, %d articles remaining", s, len(articles))
			}
		}

		result := paginateArticles(articles, page, limit)

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

		log.Printf("[INFO] DataArticlesHandler: domain=%s returning %d bytes", domain, len(out))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.Header().Set("Cache-Control", cmsCacheControl())
		w.Write(out)
	})
}

// categoryRouteMissing reports whether the CMS says this site has no such
// category or subcategory. Mirrors oos-singlecube's resolveCategory, so the
// status agrees with what the app shows. When the CMS can't tell (a failed
// request, or a site it doesn't list) the page is served as usual.
//
// The site comes from the request's host: extractDomain prefers the Referer,
// which on a page request can be another website.
func categoryRouteMissing(req *http.Request, categorySlug, subcategorySlug string) bool {
	response, err := loadCMSCategories()
	if err != nil {
		log.Printf("[ERROR] categoryRouteMissing: categories: %v", err)
		return false
	}
	domain := middlewares.ResolveToProductionDomain(requestPublicHost(req))
	data, _ := response["data"].(map[string]interface{})
	if _, listed := domainCategories(data, domain); !listed {
		// A shop site the CMS doesn't list has no blog, so no category pages.
		return isShopSite(middlewares.GetClientConfig(req.Context()))
	}

	categories := categoryPathsFromConfig(middlewares.GetClientConfig(req.Context())).withPaths(extractSitemapCategories(response, domain))
	for _, category := range categories {
		if subcategorySlug == "" && category.Slug == categorySlug {
			return false
		}
		if subcategorySlug != "" && category.Slug != categorySlug {
			continue
		}
		// /:categorySlug may also be a subcategory's name.
		wanted := subcategorySlug
		if wanted == "" {
			wanted = categorySlug
		}
		for _, sub := range category.Subcategories {
			if sub.Slug == wanted {
				return false
			}
		}
	}
	return true
}

// legacyCategoryIDPath returns the path of the site's category or subcategory
// with CMS id id (e.g. /travel or /travel/flights), for the legacy
// /articles/category/{id} URL. found is false when the id is none of the
// site's; ok is false when the CMS can't tell, as categoryRouteMissing.
func legacyCategoryIDPath(req *http.Request, id string) (path string, found, ok bool) {
	response, err := loadCMSCategories()
	if err != nil {
		log.Printf("[ERROR] legacyCategoryIDPath: categories: %v", err)
		return "", false, false
	}
	config := middlewares.GetClientConfig(req.Context())
	domain := middlewares.ResolveToProductionDomain(requestPublicHost(req))
	data, _ := response["data"].(map[string]interface{})
	if _, listed := domainCategories(data, domain); !listed {
		return "", false, isShopSite(config)
	}
	for _, category := range categoryPathsFromConfig(config).withPaths(extractSitemapCategories(response, domain)) {
		if category.ID == id {
			return "/" + category.Slug, true, true
		}
		for _, sub := range category.Subcategories {
			if sub.ID == id {
				return "/" + category.Slug + "/" + sub.Slug, true, true
			}
		}
	}
	return "", false, true
}

// ArticleByCategoryHandler serves the category articles page using the root template.
func ArticleByCategoryHandler() http.Handler {
	return articleByCategoryHandler(pageTemplates())
}

func articleByCategoryHandler(tpl *template.Template) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		ctx := req.Context()
		config := middlewares.GetClientConfig(ctx)
		if config == nil {
			http.Error(w, "client config not found", http.StatusInternalServerError)
			return
		}

		params := httprouter.ParamsFromContext(req.Context())
		// Support legacy /articles/category/:category and new /:categorySlug routes.
		categoryID := params.ByName("category")
		if categoryID == "" {
			categoryID = params.ByName("categorySlug")
		}
		subcategorySlug := params.ByName("subcategorySlug")

		// The legacy route takes a CMS id, so only slug routes can be checked by name.
		if categorySlug := params.ByName("categorySlug"); categorySlug != "" && categoryRouteMissing(req, categorySlug, subcategorySlug) {
			serveNotFoundPage(w, req, tpl)
			return
		}
		// A site template's pages live at slug URLs: the legacy id URL moves to
		// the site's category page, and is no page for any other id.
		if categorySlug := params.ByName("categorySlug"); categorySlug == "" && usesSiteTemplate(config.Raw) {
			if path, found, ok := legacyCategoryIDPath(req, categoryID); ok {
				if !found {
					serveNotFoundPage(w, req, tpl)
					return
				}
				redirectPermanently(w, req, path, req.URL.RawQuery)
				return
			}
		}

		displayName := config.GetString("displayName")
		siteId := config.GetString("siteId")
		ga := gaSettingsFromConfig(config)
		tesseractClient := config.GetString("tesseractClient")
		tesseractCdnUrl := config.GetString("tesseract_cdn_url")
		portalStaticCdnUrl := config.GetString("portal_static_cdn_url")
		scsUrl := config.GetString("scs_url")

		if tesseractCdnUrl == "" {
			tesseractCdnUrl = "/static/tesseract"
		}

		hostname, _ := os.Hostname()
		deviceType := "\"desktop\""
		environment := "\"" + config.GetString("environment") + "\""

		// Build props for SingleCube component
		props := categoryPageProps{
			StartContentServiceOrigin: scsUrl,
			PortalStaticOrigin:        portalStaticCdnUrl,
			SiteId:                    siteId,
			Category:                  "category",
			CategoryID:                categoryID,
			TesseractClient:           tesseractClient,
			DisplayName:               displayName,
			GaId:                      ga.GaId,
		}
		propsJSON, _ := json.Marshal(props)

		// Build override config
		overrideConfig := map[string]interface{}{
			"siteId":             siteId,
			"displayName":        displayName,
			"categoryId":         categoryID,
			"seoMeta":            config.GetStringMap("seoMeta"),
			"logoUrl":            logoURLFromConfig(config),
			"articleTitleSuffix": articleTitleSuffixFromConfig(config),
		}
		configJSON, _ := json.Marshal(overrideConfig)

		defaultTitle := "Category " + categoryID + " - " + displayName
		defaultDescription := "Browse category articles on " + displayName
		seoMetaKey := categoryID
		if subcategorySlug != "" {
			// Subcategory pages use "parent/child" keys in seoMeta, e.g.
			// "kids-health/treatments".
			seoMetaKey = categoryID + "/" + subcategorySlug
		}
		pageTitle, metaDescription := pageMetaOverride(config, seoMetaKey, defaultTitle, defaultDescription)

		vars := &templateVars{
			PageTitle:              pageTitle,
			MetaDescription:        metaDescription,
			OgTitle:                pageTitle,
			OgDescription:          metaDescription,
			TwitterTitle:           pageTitle,
			TwitterDescription:     metaDescription,
			FaviconUrl:             faviconURLFromConfig(config),
			DNSPrefetch:            []string{tesseractCdnUrl, scsUrl, portalStaticCdnUrl},
			CanonicalUrl:           canonicalURL(req),
			TesseractCdnUrl:        tesseractCdnUrl,
			TesseractClient:        tesseractClient,
			SingleCubeComponent:    "\"singlecube.ArticleList\"",
			SingleCubeProps:        template.JS(string(propsJSON)),
			OverrideConfig:         template.JS(string(configJSON)),
			DeviceType:             deviceType,
			Environment:            environment,
			TsuahComment:           template.HTML(fmt.Sprintf("<!-- TSUAH: %s -->", hostname)),
			GaId:                   ga.GaId,
			GaGtm:                  ga.GaGtm,
			GaCx:                   ga.GaCx,
			GtmId:                  ga.GtmId,
			GoogleCsa:              ga.GoogleCsa,
			GoogleSiteVerification: googleSiteVerificationFromConfig(config),
		}
		applyMetaRobots(w, vars, req, metaRobotsIndexable)
		applyClientUI(vars, config)

		breadcrumbs := []breadcrumbItem{homeBreadcrumbItem(req)}
		categoryName := categoryLabel(config, categoryID, humanizeSlug(categoryID))
		if subcategorySlug != "" {
			breadcrumbs = append(breadcrumbs,
				breadcrumbItem{Name: categoryName, URL: absoluteURL(req, "/"+categoryID)},
				breadcrumbItem{Name: humanizeSlug(subcategorySlug), URL: canonicalURL(req)},
			)
		} else {
			breadcrumbs = append(breadcrumbs, breadcrumbItem{Name: categoryName, URL: canonicalURL(req)})
		}
		applyCategoryStructuredData(vars, config, req, breadcrumbs)
		applyOgDefaults(vars, config)

		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if err := tpl.ExecuteTemplate(w, "root", vars); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})
}
