package listings

import (
	"bufio"
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"html"
	"io"
	"log"
	"math"
	"net/url"
	"os"
	"regexp"
	"runtime"
	"sort"
	"strconv"
	"strings"
	"sync"
	"unicode"
)

// JSONLStore serves the listings of a JSON Lines export of the legacy business
// DB, loaded into memory once. It is the interim store: a DB-backed one will
// replace it behind the same Store interface.
//
// Search order is Yext-enriched records first, then name A to Z. A radius
// search puts the listings of the city without coordinates first, then the
// rest nearest first, ties in search order. A city's centre is the mean of
// its listings' coordinates.
type JSONLStore struct {
	all        []*indexed // every listing, at its ord
	byID       map[string]*indexed
	byCity     map[string][]*indexed // Location.key() → listings in search order
	centres    map[string]point      // Location.key() → the city's centre, for cities with coordinates
	byLat      []*indexed            // listings with coordinates, by latitude
	cities     map[string][]CityCount
	states     []StateCount
	cityByZip  map[string]string // zip → Location.key() of the city most of its listings are in
	cityBySlug map[string]string // CitySlug → Location.key() of the state with the most listings of that city
	groups     sync.Map          // groupKey → *groupMembers, the category groups searched so far
}

// point is a latitude and longitude in degrees.
type point struct{ lat, lon float64 }

// indexed is a listing with what search matches against.
type indexed struct {
	Listing
	ord        int             // its index in JSONLStore.all
	text       string          // name and categories, as matchText
	categories map[string]bool // lowercased categories
	group      string          // lowercased record group
}

// record is one line of the import, in the legacy DB's field names. Fields
// the sites don't show (menu, bios, catalog, ...) are ignored.
type record struct {
	ID              flexString        `json:"id"`
	BusinessName    flexString        `json:"business_name"`
	Title           flexString        `json:"title"`
	Address         flexString        `json:"address"`
	City            flexString        `json:"city"`
	State           flexString        `json:"state"`
	Zip             flexString        `json:"zip"`
	Lat             flexString        `json:"lat"`
	Lon             flexString        `json:"lon"`
	Phones          []json.RawMessage `json:"phones"`
	Website         flexString        `json:"website"`
	Category        flexString        `json:"category"`
	Description     flexString        `json:"description"`
	BusinessHour    flexString        `json:"business_hour"`
	PaymentOptions  flexString        `json:"payment_options"`
	SpecialOffer    flexString        `json:"special_offer"`
	SpecialOfferURL flexString        `json:"special_offer_url"`
	Image           flexStrings       `json:"image"`
	Services        flexString        `json:"services"`
	Products        flexString        `json:"products"`
	Video           flexStrings       `json:"video"`
	Group           flexString        `json:"group"`
	YextID          flexString        `json:"yext_id"`
	RecordID        flexString        `json:"record_id"`
	SuppressionID   flexString        `json:"suppression_id"`
	ChangeCode      flexString        `json:"change_code"`
}

// flexString reads a JSON string, number or null (the export has numeric ids
// and coordinates as either).
type flexString string

func (s *flexString) UnmarshalJSON(data []byte) error {
	data = bytes.TrimSpace(data)
	switch {
	case bytes.Equal(data, []byte("null")):
		*s = ""
	case len(data) > 0 && data[0] == '"':
		var v string
		if err := json.Unmarshal(data, &v); err != nil {
			return err
		}
		*s = flexString(v)
	case len(data) > 0 && (data[0] == '-' || data[0] >= '0' && data[0] <= '9'):
		*s = flexString(data)
	case bytes.Equal(data, []byte("true")), bytes.Equal(data, []byte("false")):
		*s = ""
	default:
		return fmt.Errorf("want a string or number, got %s", data)
	}
	return nil
}

// flexStrings reads an array of strings, or a single string, or null.
type flexStrings []string

func (s *flexStrings) UnmarshalJSON(data []byte) error {
	data = bytes.TrimSpace(data)
	if len(data) > 0 && data[0] == '[' {
		var items []flexString
		if err := json.Unmarshal(data, &items); err != nil {
			return err
		}
		*s = make(flexStrings, 0, len(items))
		for _, item := range items {
			*s = append(*s, string(item))
		}
		return nil
	}
	var one flexString
	if err := one.UnmarshalJSON(data); err != nil {
		return err
	}
	*s = flexStrings{string(one)}
	return nil
}

// LoadJSONL loads a listings import file (see ReadJSONL).
func LoadJSONL(path string) (*JSONLStore, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	store, err := ReadJSONL(f)
	if err != nil {
		return nil, err
	}
	log.Printf("[INFO] listings: loaded %d listings in %d cities from %s", len(store.byID), len(store.byCity), path)
	return store, nil
}

// ReadJSONL builds a store from JSON Lines, one record per line (blank lines
// skipped). Records are normalised (see normalise); a line that isn't valid
// JSON, or a record without an id, name, city or state, is logged and
// skipped, as are suppressed and deleted records. The first record of an id
// wins.
func ReadJSONL(r io.Reader) (*JSONLStore, error) {
	store := &JSONLStore{byID: map[string]*indexed{}, byCity: map[string][]*indexed{}}
	reader := bufio.NewReader(r)
	var skipped, removed, duplicates int
	for line := 1; ; line++ {
		data, err := reader.ReadBytes('\n')
		if len(bytes.TrimSpace(data)) > 0 {
			var rec record
			if jsonErr := json.Unmarshal(data, &rec); jsonErr != nil {
				log.Printf("[WARN] listings: line %d: %v", line, jsonErr)
				skipped++
			} else if l, keep, reason := normalise(rec); !keep {
				if reason == "" {
					removed++
				} else {
					log.Printf("[WARN] listings: line %d: %s", line, reason)
					skipped++
				}
			} else if _, seen := store.byID[l.ID]; seen {
				duplicates++
			} else {
				l.Group = clean(rec.Group)
				store.add(l)
			}
		}
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, err
		}
	}
	store.index()
	if skipped+removed+duplicates > 0 {
		log.Printf("[INFO] listings: skipped %d invalid, %d suppressed or deleted, %d duplicate records", skipped, removed, duplicates)
	}
	return store, nil
}

func (s *JSONLStore) add(l Listing) {
	entry := newIndexed(l)
	entry.ord = len(s.all)
	s.all = append(s.all, entry)
	s.byID[l.ID] = entry
	key := Location{City: l.City, State: l.State}.key()
	s.byCity[key] = append(s.byCity[key], entry)
}

// newIndexed is l with what search matches against.
func newIndexed(l Listing) *indexed {
	entry := &indexed{Listing: l, text: listingText(l), categories: map[string]bool{}, group: strings.ToLower(l.Group)}
	for _, c := range l.Categories {
		entry.categories[strings.ToLower(c)] = true
	}
	return entry
}

// listingText is what search matches a listing against: its name and
// categories, as matchText.
func listingText(l Listing) string {
	return matchText(l.Name + " " + strings.Join(l.Categories, " "))
}

// searchLess orders search results: Yext-enriched first, then name A to Z.
func searchLess(a, b *indexed) bool {
	if ay, by := a.Source == "yext", b.Source == "yext"; ay != by {
		return ay
	}
	an, bn := strings.ToLower(a.Name), strings.ToLower(b.Name)
	if an != bn {
		return an < bn
	}
	return a.ID < b.ID
}

// index sorts each city into search order and builds the lookups of
// radius search, Cities, States and ResolveLocation.
func (s *JSONLStore) index() {
	s.centres = map[string]point{}
	s.cities = map[string][]CityCount{}
	s.cityByZip = map[string]string{}
	s.cityBySlug = map[string]string{}
	s.byLat = nil
	stateCounts := map[string]int{}
	zipCounts := map[string]map[string]int{}
	for key, list := range s.byCity {
		sort.SliceStable(list, func(i, j int) bool { return searchLess(list[i], list[j]) })
		var sum point
		var located int
		for _, e := range list {
			if e.Lat != nil && e.Lon != nil {
				sum.lat += *e.Lat
				sum.lon += *e.Lon
				located++
				s.byLat = append(s.byLat, e)
			}
			if zip := zip5(e.Zip); zip != "" {
				if zipCounts[zip] == nil {
					zipCounts[zip] = map[string]int{}
				}
				zipCounts[zip][key]++
			}
		}
		if located > 0 {
			s.centres[key] = point{sum.lat / float64(located), sum.lon / float64(located)}
		}
		first := list[0]
		s.cities[first.State] = append(s.cities[first.State], CityCount{Name: first.City, Slug: CitySlug(first.City), State: first.State, Count: len(list)})
		stateCounts[first.State] += len(list)
	}
	sort.Slice(s.byLat, func(i, j int) bool { return *s.byLat[i].Lat < *s.byLat[j].Lat })
	for state, cities := range s.cities {
		sort.Slice(cities, func(i, j int) bool {
			if a, b := strings.ToLower(cities[i].Name), strings.ToLower(cities[j].Name); a != b {
				return a < b
			}
			return cities[i].Slug < cities[j].Slug
		})
		// The city with the most listings of a name wins its bare-name lookup;
		// a tie goes to the state code first A to Z.
		for _, c := range cities {
			key := Location{City: c.Name, State: state}.key()
			if best, ok := s.cityBySlug[c.Slug]; !ok || moreListings(len(s.byCity[key]), key, len(s.byCity[best]), best) {
				s.cityBySlug[c.Slug] = key
			}
		}
	}
	s.states = make([]StateCount, 0, len(stateCounts))
	for code, n := range stateCounts {
		s.states = append(s.states, StateCount{Code: code, Count: n})
	}
	sort.Slice(s.states, func(i, j int) bool { return s.states[i].Code < s.states[j].Code })
	for zip, counts := range zipCounts {
		best := ""
		for key, n := range counts {
			if best == "" || moreListings(n, key, counts[best], best) {
				best = key
			}
		}
		s.cityByZip[zip] = best
	}
}

// moreListings reports whether city key a with n listings beats city key b
// with m: more listings, a tie going to the key first A to Z.
func moreListings(n int, a string, m int, b string) bool {
	if n != m {
		return n > m
	}
	return a < b
}

// zip5 is the 5-digit zip of "20147" or "20147-1234", else "".
func zip5(zip string) string {
	if len(zip) >= 5 && isDigits(zip[:5]) && (len(zip) == 5 || zip[5] == '-') {
		return zip[:5]
	}
	return ""
}

func (s *JSONLStore) Available() bool { return true }

func (s *JSONLStore) Search(_ context.Context, q Query) (Result, error) {
	page, pageSize := q.Page, q.PageSize
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = DefaultPageSize
	}
	if pageSize > MaxPageSize {
		pageSize = MaxPageSize
	}
	result := Result{Listings: []Listing{}, Page: page, PageSize: pageSize}
	key := q.Location.key()
	city := s.byCity[key]
	if q.Location.IsZero() || len(city) == 0 {
		return result, nil
	}
	result.CityName = city[0].City

	m := s.matcher(q)
	// A page past any listing (and one whose offset would overflow) is empty.
	start, end := math.MaxInt, math.MaxInt
	if page <= math.MaxInt/pageSize {
		start, end = (page-1)*pageSize, page*pageSize
	}
	centre, located := s.centres[key]
	if q.RadiusMiles <= 0 || !located {
		for _, entry := range city {
			if !m.matches(entry) {
				continue
			}
			if result.Total >= start && result.Total < end {
				result.Listings = append(result.Listings, entry.Listing)
			}
			result.Total++
		}
	} else {
		found := s.within(centre, q.RadiusMiles, city, m)
		result.Total = len(found)
		for i := start; i < end && i < len(found); i++ {
			result.Listings = append(result.Listings, found[i].Listing)
		}
	}
	result.TotalPages = (result.Total + pageSize - 1) / pageSize
	return result, nil
}

// Exists reports whether Search would find any listing for q, stopping at
// the first one.
func (s *JSONLStore) Exists(_ context.Context, q Query) (bool, error) {
	key := q.Location.key()
	city := s.byCity[key]
	if q.Location.IsZero() || len(city) == 0 {
		return false, nil
	}
	m := s.matcher(q)
	centre, located := s.centres[key]
	if q.RadiusMiles <= 0 || !located {
		for _, entry := range city {
			if m.matches(entry) {
				return true, nil
			}
		}
		return false, nil
	}
	found := false
	s.eachWithin(centre, q.RadiusMiles, city, m, func(*indexed, float64) bool {
		found = true
		return false
	})
	return found, nil
}

// within returns the listings matching m within miles of centre, nearest
// first, after city's listings without coordinates; ties in search order.
func (s *JSONLStore) within(centre point, miles float64, city []*indexed, m matcher) []*indexed {
	type hit struct {
		*indexed
		miles float64
	}
	var hits []hit
	unlocated := 0
	s.eachWithin(centre, miles, city, m, func(e *indexed, d float64) bool {
		hits = append(hits, hit{e, d})
		if e.Lat == nil || e.Lon == nil {
			unlocated++
		}
		return true
	})
	located := hits[unlocated:]
	sort.Slice(located, func(i, j int) bool {
		if located[i].miles != located[j].miles {
			return located[i].miles < located[j].miles
		}
		return searchLess(located[i].indexed, located[j].indexed)
	})
	out := make([]*indexed, len(hits))
	for i, h := range hits {
		out[i] = h.indexed
	}
	return out
}

// eachWithin calls visit with each listing matching m within miles of centre
// and its distance: first city's listings without coordinates (distance 0),
// then the rest by latitude. It stops when visit returns false.
func (s *JSONLStore) eachWithin(centre point, miles float64, city []*indexed, m matcher, visit func(e *indexed, miles float64) bool) {
	for _, e := range city {
		if (e.Lat == nil || e.Lon == nil) && m.matches(e) && !visit(e, 0) {
			return
		}
	}
	span := miles / milesPerDegreeLat
	lo := sort.Search(len(s.byLat), func(i int) bool { return *s.byLat[i].Lat >= centre.lat-span })
	for _, e := range s.byLat[lo:] {
		if *e.Lat > centre.lat+span {
			return
		}
		if d := distanceMiles(centre, point{*e.Lat, *e.Lon}); d <= miles && m.matches(e) && !visit(e, d) {
			return
		}
	}
}

// milesPerDegreeLat is the length of a degree of latitude, an upper bound on
// how far a degree of latitude can be from a point (for the search window).
const milesPerDegreeLat = 69.0

// earthRadiusMiles is the mean radius of the Earth.
const earthRadiusMiles = 3958.8

// distanceMiles is the great-circle distance between two points.
func distanceMiles(a, b point) float64 {
	const rad = math.Pi / 180
	dLat, dLon := (b.lat-a.lat)*rad, (b.lon-a.lon)*rad
	h := math.Sin(dLat/2)*math.Sin(dLat/2) + math.Cos(a.lat*rad)*math.Cos(b.lat*rad)*math.Sin(dLon/2)*math.Sin(dLon/2)
	return 2 * earthRadiusMiles * math.Asin(math.Min(1, math.Sqrt(h)))
}

// matcher is a Query's text filter: Keyword, and the category group of
// AnyOf and Group.
type matcher struct {
	words []string // Keyword's words, all required
	// inGroup reports whether a listing is in the category group; nil when
	// the query has none.
	inGroup func(*indexed) bool
}

func (m matcher) matches(e *indexed) bool {
	return e.matches(m.words) && (m.inGroup == nil || m.inGroup(e))
}

// keywordWords are the words of a Query's Keyword, all of which a listing's
// name or categories must contain.
func keywordWords(q Query) []string {
	return strings.Fields(matchText(q.Keyword))
}

// Matcher is a Query's text filter (Keyword, and the category group of AnyOf
// and Group) compiled once, to test listings as Search matches them; q's
// location is not checked.
type Matcher struct {
	m matcher
}

// NewMatcher compiles q's text filter.
func NewMatcher(q Query) Matcher {
	m := matcher{words: keywordWords(q)}
	if g := newCategoryGroup(q); g != nil {
		m.inGroup = g.has
	}
	return Matcher{m}
}

// Matches reports whether l passes the filter.
func (m Matcher) Matches(l Listing) bool {
	return m.m.matches(&indexed{text: listingText(l), group: strings.ToLower(l.Group)})
}

// categoryGroup is the category group of a Query's AnyOf and Group (see
// Query): a listing is in it when its record's group is the label, or every
// word of one of the terms starts a word of its listingText ("Pet Sitting" is
// in "Pet & Animal Sitting", "Appliance Dealers" in "Appliances Dealers",
// "Arts" is not in "Auto Parts").
type categoryGroup struct {
	words   map[string]int // every word of the terms → its id
	terms   [][]int        // each term's word ids
	byFirst [][]int        // word id → the terms whose first word it is
	label   string         // lowercased Group
}

// newCategoryGroup compiles q's category group; nil when it has none (no
// Group and no AnyOf term with a word).
func newCategoryGroup(q Query) *categoryGroup {
	g := &categoryGroup{words: map[string]int{}, label: strings.ToLower(strings.TrimSpace(q.Group))}
	for _, term := range q.AnyOf {
		words := strings.Fields(matchText(term))
		if len(words) == 0 {
			continue
		}
		ids := make([]int, len(words))
		for i, w := range words {
			id, ok := g.words[w]
			if !ok {
				id = len(g.words)
				g.words[w] = id
				g.byFirst = append(g.byFirst, nil)
			}
			ids[i] = id
		}
		g.byFirst[ids[0]] = append(g.byFirst[ids[0]], len(g.terms))
		g.terms = append(g.terms, ids)
	}
	if len(g.terms) == 0 && g.label == "" {
		return nil
	}
	return g
}

// has reports whether e is in the group: its record's group is the label, or
// every word of a term is the start of one of its words.
func (g *categoryGroup) has(e *indexed) bool {
	if g.label != "" && e.group == g.label {
		return true
	}
	// The term words that start one of e's words (on the stack for a usual
	// listing).
	var buf [64]int
	found := buf[:0]
	text := e.text // matchText: words joined by single spaces
	for start := 0; start < len(text); {
		end := strings.IndexByte(text[start:], ' ')
		if end < 0 {
			end = len(text)
		} else {
			end += start
		}
		for k := start + 1; k <= end; k++ {
			if id, ok := g.words[text[start:k]]; ok {
				found = append(found, id)
			}
		}
		start = end + 1
	}
	for _, first := range found {
		for _, t := range g.byFirst[first] {
			if containsAll(found, g.terms[t][1:]) {
				return true
			}
		}
	}
	return false
}

// containsAll reports whether every id of want is in ids.
func containsAll(ids, want []int) bool {
	for _, w := range want {
		in := false
		for _, id := range ids {
			if id == w {
				in = true
				break
			}
		}
		if !in {
			return false
		}
	}
	return true
}

// groupMembers is a category group's members in a store, worked out at its
// first search.
type groupMembers struct {
	group *categoryGroup // nil: q had no group
	once  sync.Once
	bits  []uint64 // bit ord is set when the listing at that ord is in the group
}

// groupKey names q's category group as the query spells it.
func groupKey(q Query) string {
	return strings.Join(q.AnyOf, "\x00") + "\x01" + q.Group
}

// matcher is q's text filter for a search of this store. A category group's
// members are worked out once, at its first search, over every listing on a
// fixed pool of GOMAXPROCS workers, and kept (a bit per listing): later
// searches of the group only test a listing's bit.
func (s *JSONLStore) matcher(q Query) matcher {
	m := matcher{words: keywordWords(q)}
	if len(q.AnyOf) == 0 && q.Group == "" {
		return m
	}
	key := groupKey(q)
	cached, ok := s.groups.Load(key)
	if !ok {
		cached, _ = s.groups.LoadOrStore(key, &groupMembers{group: newCategoryGroup(q)})
	}
	members := cached.(*groupMembers)
	if members.group == nil {
		return m
	}
	members.once.Do(func() { members.bits = s.members(members.group) })
	bits := members.bits
	m.inGroup = func(e *indexed) bool { return bits[e.ord>>6]&(1<<(e.ord&63)) != 0 }
	return m
}

// members is the bitset of the listings in g, by ord.
func (s *JSONLStore) members(g *categoryGroup) []uint64 {
	bits := make([]uint64, (len(s.all)+63)/64)
	workers := runtime.GOMAXPROCS(0)
	per := (len(bits) + workers - 1) / workers // words of bits per worker, so none share one
	var wg sync.WaitGroup
	for lo := 0; lo < len(bits); lo += per {
		wg.Add(1)
		go func(lo, hi int) {
			defer wg.Done()
			for ord := lo * 64; ord < hi*64 && ord < len(s.all); ord++ {
				if g.has(s.all[ord]) {
					bits[ord>>6] |= 1 << (ord & 63)
				}
			}
		}(lo, min(lo+per, len(bits)))
	}
	wg.Wait()
	return bits
}

func (s *JSONLStore) Get(_ context.Context, id string) (Listing, bool, error) {
	entry, ok := s.byID[id]
	if !ok {
		return Listing{}, false, nil
	}
	return entry.Listing, true, nil
}

func (s *JSONLStore) Nearby(_ context.Context, l Listing, keyword string, n int) ([]Listing, error) {
	out := []Listing{}
	words := strings.Fields(matchText(keyword))
	for _, entry := range s.byCity[Location{City: l.City, State: l.State}.key()] {
		if len(out) >= n {
			break
		}
		if entry.ID == l.ID {
			continue
		}
		if entry.sharesCategory(l.Categories) || len(words) > 0 && entry.matches(words) {
			out = append(out, entry.Listing)
		}
	}
	return out, nil
}

func (s *JSONLStore) Cities(_ context.Context, state string) ([]CityCount, error) {
	cities := s.cities[strings.ToUpper(state)]
	out := make([]CityCount, len(cities))
	copy(out, cities)
	return out, nil
}

func (s *JSONLStore) States(context.Context) ([]StateCount, error) {
	out := make([]StateCount, len(s.states))
	copy(out, s.states)
	return out, nil
}

// ResolveLocation reads input as resolveLocation does, against the cities
// of the listings: a zip is its listings' city, a bare city the state with
// the most listings of that city.
func (s *JSONLStore) ResolveLocation(ctx context.Context, input string) (Location, bool, error) {
	return resolveLocation(ctx, input, s)
}

func (s *JSONLStore) zipLocation(_ context.Context, zip string) (Location, bool, error) {
	key, ok := s.cityByZip[zip]
	if !ok {
		return Location{}, false, nil
	}
	return s.location(key), true, nil
}

func (s *JSONLStore) stateLocation(_ context.Context, city, state string) (Location, bool, error) {
	l, ok := s.cityInState(city, state)
	return l, ok, nil
}

func (s *JSONLStore) slugLocation(_ context.Context, slug string) (Location, bool, error) {
	key, ok := s.cityBySlug[slug]
	if !ok {
		return Location{}, false, nil
	}
	return s.location(key), true, nil
}

// locationSuffixRe matches a country ("USA", "US", "United States [of
// America]") or a zip ("20147", "20147-1234") at the end of a typed location,
// after a comma or space.
var locationSuffixRe = regexp.MustCompile(`(?i)[\s,]+(?:usa|us|united\s+states(?:\s+of\s+america)?|[0-9]{5}(?:-[0-9]{4})?)$`)

// trimLocationSuffixes drops a trailing country and zip from a typed location
// ("Ashburn, VA, USA", "Ashburn VA 20147" → "Ashburn, VA", "Ashburn VA"),
// never the whole of it (a bare zip stays).
func trimLocationSuffixes(s string) string {
	for {
		trimmed := strings.TrimRight(locationSuffixRe.ReplaceAllString(s, ""), ", \t")
		if trimmed == s || trimmed == "" {
			return s
		}
		s = trimmed
	}
}

// cityInState returns the city with listings named city in state.
func (s *JSONLStore) cityInState(city, state string) (Location, bool) {
	state = strings.TrimSpace(state)
	if !IsStateCode(state) || CitySlug(city) == "" {
		return Location{}, false
	}
	key := Location{City: city, State: state}.key()
	if _, ok := s.byCity[key]; !ok {
		return Location{}, false
	}
	return s.location(key), true
}

// location is the Location of a city key, spelled as its listings spell it.
func (s *JSONLStore) location(key string) Location {
	first := s.byCity[key][0]
	return Location{City: first.City, State: first.State}
}

// cityWords is a typed city with hyphens read as spaces and runs of spaces
// collapsed ("los-angeles " → "los angeles").
func cityWords(s string) string {
	return strings.Join(strings.Fields(strings.ReplaceAll(s, "-", " ")), " ")
}

// matches reports whether every word is in the listing's name or categories.
func (e *indexed) matches(words []string) bool {
	for _, w := range words {
		if !strings.Contains(e.text, w) {
			return false
		}
	}
	return true
}

func (e *indexed) sharesCategory(categories []string) bool {
	for _, c := range categories {
		if e.categories[strings.ToLower(c)] {
			return true
		}
	}
	return false
}

// matchTextReplacer spells "&" "and" and drops apostrophes, for matchText.
var matchTextReplacer = strings.NewReplacer("&", " and ", "'", "", "’", "")

// matchText is s as search compares it: lowercase, "&" spelled "and",
// apostrophes dropped, anything else that isn't a letter or digit a space.
func matchText(s string) string {
	s = matchTextReplacer.Replace(strings.ToLower(s))
	return strings.Join(strings.FieldsFunc(s, func(r rune) bool {
		return !unicode.IsLetter(r) && !unicode.IsDigit(r)
	}), " ")
}

// normalise turns an import record into a Listing:
//   - every value trimmed, inner runs of whitespace one space, and lists split
//     on commas without empty items (the trailing comma of payment_options,
//     which also splits on "::");
//   - description and business_hour read as text lines (see textLines):
//     description paragraphs joined with "\n", hours one line per day;
//   - services and products as plain text (see plainText);
//   - video URLs read as YouTube video ids (see youTubeIDs);
//   - the website's feed form "website~~https://x||https://x" read as
//     https://x, and a bare www.x.com as https://www.x.com;
//   - http image URLs on the Yext CDNs (a.mktgcdn.com, www.yext-static.com)
//     made https;
//   - phones formatted "(AAA) BBB-CCCC" (ones without a 10-digit US number
//     are dropped);
//   - source from yext_id, else the record_id prefix.
//
// keep is false for a suppressed or deleted (change_code "D") record, with
// reason "", and for an invalid one, with the reason.
func normalise(rec record) (l Listing, keep bool, reason string) {
	if clean(rec.SuppressionID) != "" || strings.EqualFold(clean(rec.ChangeCode), "D") {
		return Listing{}, false, ""
	}
	l = Listing{
		ID:             clean(rec.ID),
		Name:           clean(rec.BusinessName),
		Address:        clean(rec.Address),
		City:           clean(rec.City),
		State:          strings.ToUpper(clean(rec.State)),
		Zip:            clean(rec.Zip),
		Lat:            coordinate(clean(rec.Lat), 90),
		Lon:            coordinate(clean(rec.Lon), 180),
		Phones:         phones(rec.Phones),
		Website:        website(clean(rec.Website)),
		Categories:     list(clean(rec.Category)),
		Description:    strings.Join(textLines(string(rec.Description)), "\n"),
		Hours:          textLines(string(rec.BusinessHour)),
		Services:       plainText(string(rec.Services)),
		Products:       plainText(string(rec.Products)),
		PaymentOptions: list(strings.ReplaceAll(clean(rec.PaymentOptions), "::", ",")),
		Images:         images(rec.Image),
		Videos:         youTubeIDs(rec.Video),
		YextID:         clean(rec.YextID),
		Source:         source(clean(rec.YextID), clean(rec.RecordID)),
	}
	if l.Name == "" {
		l.Name = clean(rec.Title)
	}
	if text, link := clean(rec.SpecialOffer), webURL(clean(rec.SpecialOfferURL)); text != "" || link != "" {
		l.SpecialOffer = &SpecialOffer{Text: text, URL: link}
	}
	switch {
	case !isDigits(l.ID):
		return Listing{}, false, fmt.Sprintf("id %q is not numeric", l.ID)
	case l.Name == "":
		return Listing{}, false, "listing " + l.ID + " has no name"
	case l.City == "" || CitySlug(l.City) == "":
		return Listing{}, false, "listing " + l.ID + " has no city"
	case !IsStateCode(l.State):
		return Listing{}, false, fmt.Sprintf("listing %s has state %q", l.ID, l.State)
	}
	l.URL = ListingURL(l.State, l.City, l.ID, l.Name)
	return l, true, ""
}

// clean trims s and makes each inner run of whitespace one space.
func clean(s flexString) string {
	return strings.Join(strings.Fields(string(s)), " ")
}

// list splits a comma list, dropping empty items.
func list(s string) []string {
	out := []string{}
	for _, item := range strings.Split(s, ",") {
		if item = strings.TrimSpace(item); item != "" {
			out = append(out, item)
		}
	}
	return out
}

func coordinate(s string, limit float64) *float64 {
	if s == "" {
		return nil
	}
	v, err := strconv.ParseFloat(s, 64)
	if err != nil || v < -limit || v > limit || v == 0 {
		return nil
	}
	return &v
}

func isDigits(s string) bool {
	if s == "" {
		return false
	}
	for _, r := range s {
		if r < '0' || r > '9' {
			return false
		}
	}
	return true
}

// website reads the feed's "website~~https://x||https://x" form and a bare
// host ("www.x.com" → "https://www.x.com"); see webURL.
func website(s string) string {
	if _, rest, ok := strings.Cut(s, "~~"); ok {
		s = rest
	}
	for _, part := range strings.Split(s, "||") {
		if part = strings.TrimSpace(part); part != "" {
			if !strings.Contains(part, "://") {
				part = "https://" + part
			}
			return webURL(part)
		}
	}
	return ""
}

// webURL returns s when it is an absolute http(s) URL, else "".
func webURL(s string) string {
	u, err := url.Parse(s)
	if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
		return ""
	}
	return s
}

// yextImageHosts serve the Yext images, which the export has as http URLs.
var yextImageHosts = map[string]bool{"a.mktgcdn.com": true, "www.yext-static.com": true}

func images(in flexStrings) []string {
	out := []string{}
	for _, item := range in {
		src := webURL(clean(flexString(item)))
		if src == "" {
			continue
		}
		if u, _ := url.Parse(src); u.Scheme == "http" && yextImageHosts[strings.ToLower(u.Host)] {
			u.Scheme = "https"
			src = u.String()
		}
		out = append(out, src)
	}
	return out
}

// phoneLabelRe finds the label of "(703) 723-8440 (Main)".
var phoneLabelRe = regexp.MustCompile(`\(([^()]*[^()0-9\s-][^()]*)\)\s*$`)

// phones reads the phone entries: "(703) 723-8440 (Main)", "1:7188851220:Main"
// or {"number": "...", "label": "..."}.
func phones(raw []json.RawMessage) []Phone {
	out := []Phone{}
	for _, item := range raw {
		var number, label string
		var obj struct {
			Number flexString `json:"number"`
			Label  flexString `json:"label"`
		}
		var text flexString
		if err := json.Unmarshal(item, &obj); err == nil {
			number, label = clean(obj.Number), clean(obj.Label)
		} else if err := json.Unmarshal(item, &text); err == nil {
			number = clean(text)
			if m := phoneLabelRe.FindStringSubmatchIndex(number); m != nil {
				label, number = strings.TrimSpace(number[m[2]:m[3]]), number[:m[0]]
			} else if parts := strings.Split(number, ":"); len(parts) == 3 {
				number, label = parts[1], strings.TrimSpace(parts[2])
			}
		}
		if phone, ok := formatPhone(number, label); ok {
			out = append(out, phone)
		}
	}
	return out
}

// formatPhone formats a 10-digit US number (an 11-digit one starting with 1
// too); ok is false for anything else.
func formatPhone(number, label string) (Phone, bool) {
	var digits strings.Builder
	for _, r := range number {
		if r >= '0' && r <= '9' {
			digits.WriteRune(r)
		}
	}
	d := digits.String()
	if len(d) == 11 && d[0] == '1' {
		d = d[1:]
	}
	if len(d) != 10 {
		return Phone{}, false
	}
	return Phone{
		Number: "(" + d[:3] + ") " + d[3:6] + "-" + d[6:],
		Tel:    "+1" + d,
		Label:  label,
	}, true
}

// source names the record's feed: "yext" when it has a yext_id, else the
// record_id prefix ("yext-", "localeze-", "ll-"), else "".
func source(yextID, recordID string) string {
	if yextID != "" {
		return "yext"
	}
	prefix, _, ok := strings.Cut(strings.ToLower(recordID), "-")
	if ok {
		switch prefix {
		case "yext", "localeze", "ll":
			return prefix
		}
	}
	return ""
}

// brRe matches an HTML line break: <br>, <br/>, <br />, any case.
var brRe = regexp.MustCompile(`(?i)<br\s*/?>`)

// tagRe matches an HTML tag.
var tagRe = regexp.MustCompile(`<[^>]*>`)

// textLines reads an HTML fragment as lines of plain text: <br> and newlines
// break lines, other tags are dropped, entities decoded, and each line
// trimmed with inner runs of whitespace one space; empty lines are dropped.
func textLines(s string) []string {
	s = tagRe.ReplaceAllString(brRe.ReplaceAllString(s, "\n"), "")
	out := []string{}
	for _, line := range strings.Split(html.UnescapeString(s), "\n") {
		if line = clean(flexString(line)); line != "" {
			out = append(out, line)
		}
	}
	return out
}

// plainText is an HTML fragment as one line of text: tags dropped, entities
// decoded, whitespace collapsed (as a browser shows it).
func plainText(s string) string {
	return clean(flexString(html.UnescapeString(tagRe.ReplaceAllString(s, ""))))
}

// youTubeIDRe is a YouTube video id.
var youTubeIDRe = regexp.MustCompile(`^[A-Za-z0-9_-]{11}$`)

// youTubeIDs reads the video ids of YouTube URLs (watch?v=, youtu.be/,
// /embed/), dropping other URLs and repeats.
func youTubeIDs(in flexStrings) []string {
	out := []string{}
	seen := map[string]bool{}
	for _, item := range in {
		u, err := url.Parse(clean(flexString(item)))
		if err != nil {
			continue
		}
		host := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
		var id string
		switch {
		case host == "youtu.be":
			id = strings.Trim(u.Path, "/")
		case host == "youtube.com" || host == "m.youtube.com" || host == "youtube-nocookie.com":
			if rest, ok := strings.CutPrefix(u.Path, "/embed/"); ok {
				id = strings.Trim(rest, "/")
			} else if u.Path == "/watch" {
				id = u.Query().Get("v")
			}
		}
		if youTubeIDRe.MatchString(id) && !seen[id] {
			seen[id] = true
			out = append(out, id)
		}
	}
	return out
}
