package routes

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

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

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

// ArticleDetailHandler serves the article detail page using the root template.
func ArticleDetailHandler() http.Handler {
	return articleDetailHandler(pageTemplates())
}

// articleDetailHandler is ArticleDetailHandler rendering with tpl.
func articleDetailHandler(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
		}

		route := resolveArticleRoute(req, config, httprouter.ParamsFromContext(req.Context()), req.URL.Path)
		if route.NotFoundPage {
			serveNotFoundPage(w, req, tpl)
			return
		}
		if route.Redirect != "" {
			redirectPermanently(w, req, route.Redirect, req.URL.RawQuery)
			return
		}
		articleID, meta, metaLoaded, articleMissing := route.ID, route.Meta, route.MetaLoaded, route.Missing

		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 := articleDetailProps{
			StartContentServiceOrigin: scsUrl,
			PortalStaticOrigin:        portalStaticCdnUrl,
			SiteId:                    siteId,
			ArticleID:                 articleID,
			TesseractClient:           tesseractClient,
			DisplayName:               displayName,
			GaId:                      ga.GaId,
		}
		propsJSON, _ := json.Marshal(props)

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

		pageTitle := "Article - " + displayName
		metaDescription := "Read article on " + displayName

		vars := &templateVars{
			PageTitle:              pageTitle,
			MetaDescription:        metaDescription,
			FaviconUrl:             faviconURLFromConfig(config),
			DNSPrefetch:            []string{tesseractCdnUrl, scsUrl, portalStaticCdnUrl},
			CanonicalUrl:           canonicalURL(req),
			TesseractCdnUrl:        tesseractCdnUrl,
			TesseractClient:        tesseractClient,
			SingleCubeComponent:    "\"singlecube.ArticleDetail\"",
			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),
		}

		breadcrumbs := []breadcrumbItem{homeBreadcrumbItem(req)}
		if metaLoaded {
			titleSuffixName := displayName
			if !articleTitleSuffixFromConfig(config) {
				titleSuffixName = ""
			}
			// The site's menu label for the category (CMS names can differ in case),
			// also in the keywords when they fall back to the category.
			categorySlug := categoryPathsFromConfig(config).slug(meta.Category)
			section := categoryLabel(config, categorySlug, meta.Category)
			if meta.KeywordsFromCategory {
				meta.Keywords = categoryKeywords(section, meta.SubCategory)
			}
			meta.applyTo(vars, titleSuffixName)
			// The site's own article <title> format replaces "{title} - {site}"; og/twitter keep the bare title.
			if pattern := articleTitlePattern(config); pattern != "" && meta.Title != "" {
				vars.PageTitle = expandArticleTitlePattern(pattern, meta.Title, meta.CMSTitle)
			}
			// Skip a crumb whose slug would be empty, so no crumb URL is "/"
			// or starts with "//".
			if categorySlug != "" {
				vars.ArticleSection = section
				breadcrumbs = append(breadcrumbs, breadcrumbItem{
					Name: section,
					URL:  absoluteURL(req, "/"+categorySlug),
				})
				if subcategorySlug := slugify(meta.SubCategory); subcategorySlug != "" {
					breadcrumbs = append(breadcrumbs, breadcrumbItem{
						Name: meta.SubCategory,
						URL:  absoluteURL(req, "/"+categorySlug+"/"+subcategorySlug),
					})
				}
			}
			if meta.Title != "" {
				breadcrumbs = append(breadcrumbs, breadcrumbItem{Name: meta.Title, URL: canonicalURL(req)})
			}
		}
		robotsKind := metaRobotsArticle
		if articleMissing {
			// No such article: the app shows its not-found page, so this is a
			// 404 with noindex and no canonical or Article data. A failed CMS
			// request is not a missing article and keeps the page indexable.
			robotsKind = metaRobotsNotFound
			vars.CanonicalUrl = ""
			if label := siteTemplatePageLabel(config.Raw, notFoundPageName); label != "" {
				vars.PageTitle = label + " - " + displayName
			}
		}
		applyMetaRobots(w, vars, req, robotsKind)
		applyClientUI(vars, config)
		if metaLoaded {
			applyArticleStructuredData(vars, config, req, breadcrumbs)
		}
		applyOgDefaults(vars, config)

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

// articleRoute is how the article page answers an article URL (see
// resolveArticleRoute).
type articleRoute struct {
	ID         string
	Meta       articlePageMeta
	MetaLoaded bool
	// Missing: no article to show here, so the page is a 404 (unless Redirect
	// or NotFoundPage says otherwise).
	Missing bool
	// Redirect is the path to 301 to instead: a deleted article's listing, or
	// the article's canonical URL. "" for none.
	Redirect string
	// NotFoundPage: answer with the site's plain not-found page.
	NotFoundPage bool
}

// resolveArticleRoute works out how the article page answers path, an article
// URL whose route params are params ("category", "subcategory", "slug").
//
// The CMS meta is fetched up-front: it gives the page meta and breadcrumbs,
// and shows legacy/subcategory-less or title-less URLs that redirect to their
// canonical form. An ID that isn't all digits ("1760806x") is no article: the
// CMS answers it with an error rather than {"data": false}, which would
// otherwise read as a CMS failure and keep the page indexable.
func resolveArticleRoute(req *http.Request, config *middlewares.ClientConfig, params httprouter.Params, path string) articleRoute {
	route := articleRoute{ID: extractArticleIDFromSlug(params.ByName("slug"))}
	if route.Missing = !isNumericID(route.ID); route.Missing {
		return route
	}
	// A shop site the CMS doesn't list has no articles: any id is a 404, never
	// a 301 to another site's article.
	if cmsUnlistedShopSite(req) {
		route.Missing, route.NotFoundPage = true, true
		return route
	}
	route.Meta, route.MetaLoaded, route.Missing = loadArticleMeta(route.ID)
	// An article deleted from the CMS: 301 to the listing its URL names.
	// Not for a non-numeric ID or another site's article; those stay 404.
	if route.Missing {
		target := deletedArticleRedirectPath(req, params)
		// On a directory site a URL whose category isn't the site's
		// (e.g. an old /business/{id} listing URL) is a 404, never a 301 home.
		if target == "/" && isDirectorySite(config) {
			route.NotFoundPage = true
			return route
		}
		route.Redirect = target
		return route
	}
	// Another site's article is no article here.
	if route.MetaLoaded && !articleBelongsToSite(req, route.Meta.Category, route.ID) {
		route.Meta, route.MetaLoaded, route.Missing = articlePageMeta{}, false, true
	}
	// Permanently redirect legacy/non-canonical article URLs (wrong or
	// missing category/subcategory, outdated slug, trailing slash) to
	// their canonical form. An article of a category whose page shows it in
	// full (see categoryShowsArticle) has that page as its URL.
	if route.MetaLoaded {
		urlMeta := forArticleURL(route.Meta, articleURLOptionsFromConfig(config))
		if categorySlug := slugify(urlMeta.Category); categoryShowsArticle(config, categorySlug) {
			route.Redirect = "/" + categorySlug
		} else {
			route.Redirect = articleCanonicalRedirectPath(urlMeta, route.ID, path)
		}
	}
	return route
}

// nonArticleRoutePrefixes are the first segments of the routes main.go
// registers with more than one segment, other than the article ones
// (TestNonArticleRoutePrefixes_MatchMainRoutes checks them against main.go).
var nonArticleRoutePrefixes = map[string]bool{"categories": true, "info": true, "site": true, "shop": true, "product_detail": true, "data": true, "health-check": true, "survey": true, "topquiz": true, "quiz": true, "trending": true}

// articleRouteParams returns the route params the article page gets for an
// article URL, as the router and the not-found handler give them:
// /article/{id}-{slug}, /{category}/{subcategory}/{id}-{slug} or
// /{category}/{id}-{slug}. ok is false for any other path, and for the URLs
// of main.go's other routes (/categories/24-hour-plumbers, /info/1...).
func articleRouteParams(path string) (httprouter.Params, bool) {
	first, _, _ := strings.Cut(strings.TrimPrefix(path, "/"), "/")
	if nonArticleRoutePrefixes[first] || strings.HasPrefix(path, "/articles/category/") {
		return nil, false
	}
	if category, subcategory, slug, ok := parseSubcategoryArticleDetailPath(path); ok {
		return httprouter.Params{{Key: "category", Value: category}, {Key: "subcategory", Value: subcategory}, {Key: "slug", Value: slug}}, true
	}
	category, slug, ok := parseArticleDetailPath(path)
	if !ok {
		return nil, false
	}
	if category == "article" {
		// The /article/:slug route has no category.
		return httprouter.Params{{Key: "slug", Value: slug}}, true
	}
	return httprouter.Params{{Key: "category", Value: category}, {Key: "slug", Value: slug}}, true
}

// loadArticleMeta loads an article from the CMS (cached) and parses its SEO
// meta. ok is false when there is no meta to use; missing is true only when
// the CMS answered that there is no such article ({"data": false}), not when
// the request failed or the response didn't parse.
func loadArticleMeta(articleID string) (meta articlePageMeta, ok, missing bool) {
	data, err := cmsService.GetArticle(articleID)
	if err != nil {
		log.Printf("[WARN] could not load article id=%s: %v", articleID, err)
		return articlePageMeta{}, false, false
	}
	meta = articlePageMetaFromCMS(data)
	return meta, meta != articlePageMeta{}, cmsArticleMissing(data)
}

// deletedArticleRedirectPath is where a deleted article's URL goes. The CMS
// keeps nothing of a deleted article, so the listing comes from the URL:
// /{category}/{subcategory}/{id}-{slug} goes to the subcategory, else
// /{category}/{id}-{slug} to the category, when the site has it; anything
// else (e.g. /article/{id}-{slug}, or a category the site doesn't have) home.
func deletedArticleRedirectPath(req *http.Request, params httprouter.Params) string {
	category, subcategory := params.ByName("category"), params.ByName("subcategory")
	if category == "" {
		return "/"
	}
	if subcategory != "" && !categoryRouteMissing(req, category, subcategory) {
		return "/" + category + "/" + subcategory
	}
	if !categoryRouteMissing(req, category, "") {
		return "/" + category
	}
	return "/"
}

// cmsArticleMissing reports whether a getarticledata response is the CMS's
// answer for an unknown article id: {"data": false}.
func cmsArticleMissing(data []byte) bool {
	var response struct {
		Data json.RawMessage `json:"data"`
	}
	return json.Unmarshal(data, &response) == nil && string(response.Data) == "false"
}
