// Package quizsource reads quizzes, polls and their listings from a legacy quiz site
// (aboutharmony.com's PHP site) so oos-service can serve them as JSON to a frontend
// template. The source is the legacy site's HTML and its two result endpoints; nothing
// here writes to it except a vote or the answers of a finished quiz, which are posted
// to the same endpoints the legacy pages post them to.
//
// The HTML is parsed with regular expressions against the legacy markup, which is
// generated by one template, so the patterns are specific to it. When the markup changes
// the parsers fail closed: they return fewer items or an error, never invented content.
package quizsource

import (
	"encoding/json"
	"errors"
	"fmt"
	"html"
	"io"
	"net/http"
	"net/url"
	"regexp"
	"strings"
	"time"

	"bitbucket.org/imediabrands/oos-service/internal/cache"
)

// Card is a quiz as listed: on the homepage carousel, in a listing or a rail.
type Card struct {
	Slug        string `json:"slug"`
	Title       string `json:"title"`
	Image       string `json:"image,omitempty"`
	Description string `json:"description,omitempty"`
	// Posted is the legacy "Posted 1 month ago by Name" line, Author just the name.
	Posted string `json:"posted,omitempty"`
	Author string `json:"author,omitempty"`
}

// Listing is what a legacy listing page shows.
type Listing struct {
	Featured []Card `json:"featured"`
	Items    []Card `json:"items"`
	Trending []Card `json:"trending"`
	// Latest is the "Latest Buzzes" list that follows the trending one in the side column.
	Latest []Card `json:"latest"`
}

// Answer is one choice of a question or poll.
type Answer struct {
	ID   string `json:"id"`
	Text string `json:"text"`
}

// Question is one step of a quiz, or the single question of a poll.
type Question struct {
	ID      string   `json:"id"`
	Text    string   `json:"text"`
	Image   string   `json:"image,omitempty"`
	Answers []Answer `json:"answers"`
}

// Quiz types: "personality" (answers add up to a result the legacy site computes) and "poll"
// (one question, the votes so far come back with a vote). Anything else is "other", which the
// frontend does not play.
const (
	TypePersonality = "personality"
	TypePoll        = "poll"
	TypeOther       = "other"
)

// Quiz is one playable page.
type Quiz struct {
	Slug      string `json:"slug"`
	Title     string `json:"title"`
	Type      string `json:"type"`
	DisplayID string `json:"displayId"`
	Image     string `json:"image,omitempty"`
	// Author and Created are the "Created by ... on ..." byline.
	Author    string     `json:"author,omitempty"`
	Created   string     `json:"created,omitempty"`
	Questions []Question `json:"questions"`
	// Related are the "More from ..." cards under the quiz.
	Related []Card `json:"related"`
}

// Source reads one legacy site.
type Source struct {
	base   string
	client *http.Client
	cache  *cache.Cache
}

// New returns a Source for the legacy site at baseURL ("https://aboutharmony.com"). Pages are cached for ttl.
func New(baseURL string, ttl time.Duration) *Source {
	return &Source{
		base:   strings.TrimRight(baseURL, "/"),
		client: &http.Client{Timeout: 12 * time.Second},
		cache:  cache.New(ttl),
	}
}

// ErrNotFound is returned for a page the legacy site does not have.
var ErrNotFound = errors.New("quizsource: not found")

const maxBody = 4 << 20

func (s *Source) fetch(path string) (string, error) {
	req, err := http.NewRequest(http.MethodGet, s.base+path, nil)
	if err != nil {
		return "", err
	}
	req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; oos-service quiz source)")
	resp, err := s.client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode == http.StatusNotFound {
		return "", ErrNotFound
	}
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("quizsource: %s answered %d", path, resp.StatusCode)
	}
	body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody))
	return string(body), err
}

var (
	listingPathRe = regexp.MustCompile(`^/[A-Za-z0-9_-]{0,40}$`)
	slugRe        = regexp.MustCompile(`^[a-z0-9-]{1,160}$`)
)

// ValidListingPath reports whether path is a listing page of the legacy site: "/" or one lowercase/camelCase segment.
func ValidListingPath(path string) bool { return listingPathRe.MatchString(path) }

// ValidSlug reports whether slug can be a quiz slug.
func ValidSlug(slug string) bool { return slugRe.MatchString(slug) }

// Listing returns the cards of a listing page ("/" is the homepage), cached.
func (s *Source) Listing(path string) (*Listing, error) {
	if !ValidListingPath(path) {
		return nil, ErrNotFound
	}
	if data, ok := s.cache.Get("listing:" + path); ok {
		var l Listing
		if json.Unmarshal(data, &l) == nil {
			return &l, nil
		}
	}
	page, err := s.fetch(path)
	if err != nil {
		return nil, err
	}
	l := ParseListing(page)
	if data, err := json.Marshal(l); err == nil {
		s.cache.Set("listing:"+path, data)
	}
	return l, nil
}

// Search returns the cards the legacy site's search finds for term (1 to 80 characters), cached.
func (s *Source) Search(term string) (*Listing, error) {
	term = strings.TrimSpace(term)
	if term == "" || len([]rune(term)) > 80 {
		return nil, ErrNotFound
	}
	key := "search:" + strings.ToLower(term)
	if data, ok := s.cache.Get(key); ok {
		var l Listing
		if json.Unmarshal(data, &l) == nil {
			return &l, nil
		}
	}
	page, err := s.fetch("/search?search=" + url.QueryEscape(term))
	if err != nil {
		return nil, err
	}
	l := ParseListing(page)
	if data, err := json.Marshal(l); err == nil {
		s.cache.Set(key, data)
	}
	return l, nil
}

// Quiz returns a quiz page by slug, cached.
func (s *Source) Quiz(slug string) (*Quiz, error) {
	if !ValidSlug(slug) {
		return nil, ErrNotFound
	}
	if data, ok := s.cache.Get("quiz:" + slug); ok {
		var q Quiz
		if json.Unmarshal(data, &q) == nil {
			return &q, nil
		}
	}
	page, err := s.fetch("/survey/" + slug)
	if err != nil {
		return nil, err
	}
	q := ParseQuiz(slug, page)
	if q.Title == "" {
		return nil, ErrNotFound
	}
	if data, err := json.Marshal(q); err == nil {
		s.cache.Set("quiz:"+slug, data)
	}
	return q, nil
}

// Choice is one answer given to a question of a personality quiz.
type Choice struct {
	QuestionID string `json:"questionId"`
	AnswerID   string `json:"answerId"`
}

var idRe = regexp.MustCompile(`^[0-9]{1,12}$`)
var displayIDRe = regexp.MustCompile(`^[a-f0-9]{8,64}$`)

// PersonalityResult posts the answers of a finished personality quiz to the legacy site, which
// picks the result, and returns its answer (the legacy JSON: {"success": true, "result": {...}}).
func (s *Source) PersonalityResult(displayID string, choices []Choice) (json.RawMessage, error) {
	if !displayIDRe.MatchString(displayID) || len(choices) == 0 || len(choices) > 100 {
		return nil, ErrNotFound
	}
	type legacyChoice struct {
		QuesID string `json:"ques_id"`
		AnsID  string `json:"ans_id"`
	}
	list := make([]legacyChoice, 0, len(choices))
	for _, c := range choices {
		if !idRe.MatchString(c.QuestionID) || !idRe.MatchString(c.AnswerID) {
			return nil, ErrNotFound
		}
		list = append(list, legacyChoice{QuesID: c.QuestionID, AnsID: c.AnswerID})
	}
	encoded, _ := json.Marshal(list)
	return s.post("/results/personalityQuiz", url.Values{"quizDisplayId": {displayID}, "results": {string(encoded)}})
}

// PollVote posts a vote to the legacy site and returns its answer ({"success": true, "result": [{id, count}, ...]}).
func (s *Source) PollVote(displayID, optionID string) (json.RawMessage, error) {
	if !displayIDRe.MatchString(displayID) || !idRe.MatchString(optionID) {
		return nil, ErrNotFound
	}
	return s.post("/results/poll", url.Values{"quizDisplayId": {displayID}, "resultId": {optionID}})
}

func (s *Source) post(path string, form url.Values) (json.RawMessage, error) {
	req, err := http.NewRequest(http.MethodPost, s.base+path, strings.NewReader(form.Encode()))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; oos-service quiz source)")
	resp, err := s.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("quizsource: %s answered %d", path, resp.StatusCode)
	}
	body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
	if err != nil {
		return nil, err
	}
	if !json.Valid(body) {
		return nil, fmt.Errorf("quizsource: %s did not answer JSON", path)
	}
	return json.RawMessage(body), nil
}

// ── Parsing ────────────────────────────────────────────────────────────────

var (
	tagRe        = regexp.MustCompile(`(?s)<[^>]*>`)
	spaceRe      = regexp.MustCompile(`\s+`)
	scriptRe     = regexp.MustCompile(`(?s)<script\b.*?</script>|<style\b.*?</style>|<!--.*?-->`)
	surveyLinkRe = regexp.MustCompile(`/(?:survey|topquiz|quiz|trending)/([a-z0-9-]+)`)
	imgSrcRe     = regexp.MustCompile(`<img[^>]*?\bsrc="([^"]+)"`)
)

func text(s string) string {
	return strings.TrimSpace(spaceRe.ReplaceAllString(html.UnescapeString(tagRe.ReplaceAllString(s, " ")), " "))
}

func absolute(u string) string {
	u = html.UnescapeString(strings.TrimSpace(u))
	if strings.HasPrefix(u, "//") {
		return "https:" + u
	}
	return u
}

var (
	mediaItemRe   = regexp.MustCompile(`(?s)<li class="media[^"]*">(.*?)</li>`)
	postTimeRe    = regexp.MustCompile(`(?s)<span class="post-time[^"]*">(.*?)</span>`)
	h5Re          = regexp.MustCompile(`(?s)<h5[^>]*>(.*?)</h5>(.*)`)
	cardTitleRe   = regexp.MustCompile(`(?s)<div class="card-body">(.*?)</div>`)
	createdByRe   = regexp.MustCompile(`(?s)class="created-by">\s*Created by\s*(?:<a[^>]*>)?(.*?)(?:</a>)?\s*</span>`)
	createdDateRe = regexp.MustCompile(`(?s)class="created-date">(.*?)</span>`)
	trendingRe    = regexp.MustCompile(`(?s)<li>\s*(?:<a[^>]*>\s*)?<img[^>]*src="([^"]+)"[^>]*/?>\s*(?:</a>\s*)?<a href="[^"]*/(?:trending|topquiz)/([a-z0-9-]+)"[^>]*class="headline">(.*?)</a>\s*<span>(.*?)</span>`)
	byRe          = regexp.MustCompile(`^(?i)posted\b.*?\bby\s+(.*)$`)
)

// ParseListing reads the carousel, the main list and the trending rail of a legacy listing page.
func ParseListing(page string) *Listing {
	page = scriptRe.ReplaceAllString(page, "")
	l := &Listing{Featured: []Card{}, Items: []Card{}, Trending: []Card{}, Latest: []Card{}}

	// The carousel: each <div class="item"> holds a linked picture and a card-body with the title.
	for _, block := range splitBlocks(page, `<div class="item">`, `<div class="clearfix">`, `id="article-listing"`) {
		slug := firstSlug(block)
		title := ""
		if t := cardTitleRe.FindStringSubmatch(block); t != nil {
			title = text(t[1])
		}
		if slug == "" || title == "" {
			continue
		}
		l.Featured = append(l.Featured, Card{Slug: slug, Title: title, Image: firstImage(block)})
	}

	for _, m := range mediaItemRe.FindAllStringSubmatch(page, -1) {
		block := m[1]
		slug := firstSlug(block)
		h := h5Re.FindStringSubmatch(block)
		if slug == "" || h == nil {
			continue
		}
		card := Card{Slug: slug, Title: text(h[1]), Image: firstImage(block), Description: text(h[2])}
		if p := postTimeRe.FindStringSubmatch(block); p != nil {
			card.Posted = text(p[1])
			if by := byRe.FindStringSubmatch(card.Posted); by != nil {
				card.Author = strings.TrimSpace(by[1])
			}
		}
		l.Items = append(l.Items, card)
	}

	// The side column: "Trending Today", then (after its own heading) "Latest Buzzes".
	trendingPart, latestPart := page, ""
	if i := strings.Index(page, "Latest Buzz"); i >= 0 {
		trendingPart, latestPart = page[:i], page[i:]
	}
	for _, m := range trendingRe.FindAllStringSubmatch(trendingPart, -1) {
		author := strings.TrimSpace(strings.TrimPrefix(text(m[4]), "By "))
		l.Trending = append(l.Trending, Card{Slug: m[2], Title: text(m[3]), Image: absolute(m[1]), Author: author})
	}
	for _, m := range trendingRe.FindAllStringSubmatch(latestPart, -1) {
		author := strings.TrimSpace(strings.TrimPrefix(text(m[4]), "By "))
		l.Latest = append(l.Latest, Card{Slug: m[2], Title: text(m[3]), Image: absolute(m[1]), Author: author})
	}
	return l
}

// splitBlocks returns the chunks of s that start at each occurrence of marker, each running to the next one.
// The last chunk is cut at the first of stops, so it does not run on into the rest of the page.
func splitBlocks(s, marker string, stops ...string) []string {
	var out []string
	for {
		i := strings.Index(s, marker)
		if i < 0 {
			return out
		}
		s = s[i+len(marker):]
		end := strings.Index(s, marker)
		if end < 0 {
			end = len(s)
			for _, stop := range stops {
				if j := strings.Index(s, stop); j >= 0 && j < end {
					end = j
				}
			}
		}
		out = append(out, s[:end])
		s = s[end:]
	}
}

func firstSlug(block string) string {
	if m := surveyLinkRe.FindStringSubmatch(block); m != nil {
		return m[1]
	}
	return ""
}

func firstImage(block string) string {
	if m := imgSrcRe.FindStringSubmatch(block); m != nil {
		return absolute(m[1])
	}
	return ""
}

var (
	titleRe      = regexp.MustCompile(`(?s)<h3 itemprop="name">\s*<b>(.*?)</b>`)
	pageTitleRe  = regexp.MustCompile(`(?s)<title>(.*?)</title>`)
	displayIDVar = regexp.MustCompile(`quizDisplayId:\s*"([a-f0-9]+)"`)
	badgeQuesRe  = regexp.MustCompile(`(?s)<span class="badge">\s*\d+\s*</span>(.*?)</a>`)
	liAnswerRe   = regexp.MustCompile(`(?s)<li[^>]*id="liOpt_(\d+)_(\d+)"[^>]*>(.*?)</li>`)
	pollWrapRe   = regexp.MustCompile(`(?s)<div class="question-wrap\s*">(.*?)<div class="clearfix">`)
	pollQuesRe   = regexp.MustCompile(`(?s)<div class="amwidget-question poll">.*?<a href="#">(.*?)</a>`)
	pollOptionRe = regexp.MustCompile(`(?s)<li id="liOpt_(\d+)"[^>]*>(.*?)</li>`)
	linkDivRe    = regexp.MustCompile(`(?s)<div class="link">(.*?)</div>`)
)

// ParseQuiz reads a legacy quiz page: its title, type, display id, questions and the related cards.
func ParseQuiz(slug, page string) *Quiz {
	body := scriptRe.ReplaceAllString(page, "")
	q := &Quiz{Slug: slug, Type: TypeOther, Questions: []Question{}, Related: []Card{}}
	if t := titleRe.FindStringSubmatch(body); t != nil {
		q.Title = text(t[1])
	}
	if d := displayIDVar.FindStringSubmatch(page); d != nil {
		q.DisplayID = d[1]
	}
	if m := createdByRe.FindStringSubmatch(body); m != nil {
		q.Author = text(m[1])
	}
	if m := createdDateRe.FindStringSubmatch(body); m != nil {
		q.Created = strings.TrimSpace(strings.TrimPrefix(text(m[1]), "on "))
	}
	// Lists and articles have no quiz heading; their <title> is "<title> | <site>". The legacy site answers an
	// unknown slug with its homepage (200), so only a page with a "Created by" byline counts.
	if q.Title == "" && q.Author != "" {
		if t := pageTitleRe.FindStringSubmatch(body); t != nil {
			q.Title = text(t[1])
			if i := strings.LastIndex(q.Title, " | "); i > 0 {
				q.Title = strings.TrimSpace(q.Title[:i])
			}
		}
	}
	switch {
	case strings.Contains(page, "results/personalityQuiz"):
		q.Type = TypePersonality
	case strings.Contains(page, "results/poll"):
		q.Type = TypePoll
	}

	switch q.Type {
	case TypePersonality:
		for _, block := range splitBlocks(body, `<div class="question-wrap`, `result-wrap`, `Share This`) {
			ques := Question{ID: "", Image: firstImage(block), Answers: []Answer{}}
			if b := badgeQuesRe.FindStringSubmatch(block); b != nil {
				ques.Text = text(b[1])
			}
			for _, a := range liAnswerRe.FindAllStringSubmatch(block, -1) {
				ques.ID = a[1]
				ques.Answers = append(ques.Answers, Answer{ID: a[2], Text: text(a[3])})
			}
			if ques.ID != "" && ques.Text != "" && len(ques.Answers) > 0 {
				q.Questions = append(q.Questions, ques)
			}
		}
	case TypePoll:
		if w := pollWrapRe.FindStringSubmatch(body); w != nil {
			ques := Question{ID: "poll", Image: firstImage(w[1]), Answers: []Answer{}}
			if t := pollQuesRe.FindStringSubmatch(w[1]); t != nil {
				ques.Text = text(t[1])
			}
			for _, o := range pollOptionRe.FindAllStringSubmatch(w[1], -1) {
				ques.Answers = append(ques.Answers, Answer{ID: o[1], Text: text(o[2])})
			}
			if ques.Text != "" && len(ques.Answers) > 0 {
				q.Questions = append(q.Questions, ques)
			}
		}
	}
	if len(q.Questions) > 0 {
		q.Image = q.Questions[0].Image
	}

	if i := strings.Index(body, "More from"); i >= 0 {
		seen := map[string]bool{slug: true}
		for _, block := range splitBlocks(body[i:], `marginbot-18"`, `<footer`, `</section>`) {
			rs := firstSlug(block)
			label := ""
			if m := linkDivRe.FindStringSubmatch(block); m != nil {
				label = text(m[1])
			}
			if rs == "" || label == "" || seen[rs] {
				continue
			}
			seen[rs] = true
			q.Related = append(q.Related, Card{Slug: rs, Title: label, Image: firstImage(block)})
		}
	}
	return q
}
