package listings

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"

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

const (
	// apiTimeout bounds one call to the listing API: searches with categories
	// can take a minute.
	apiTimeout = 90 * time.Second
	// apiCacheEntries caps the cached API answers (each up to ~50 KB).
	apiCacheEntries = 2000
	// apiMaxPage and apiMaxCategories are the API's limits on page and on the
	// categories of one search.
	apiMaxPage       = 1000
	apiMaxCategories = 300
)

// APIStore serves the listings from the business listing API
// (businesslist/?action=...), one call per search or listing, each answer
// cached for its TTL. The request's site (see NewAPIStore) is sent as
// "site": verified (lp-) listings are only in the localpages answers.
type APIStore struct {
	baseURL    string
	apiKey     string
	site       func(context.Context) string
	httpClient *http.Client
	cache      *cache.Cache
	ttl        time.Duration

	// cityLists keeps each site's and state's cleaned getCities (see Cities),
	// which every search of a city in that state reads.
	mu        sync.Mutex
	cityLists map[string]cityList
}

type cityList struct {
	cities  []CityCount
	expires time.Time
}

// NewAPIStore returns the store for the listing API at baseURL. site names a
// request's directory site, as the API spells it (the client name, e.g.
// "localpages"); nil or "" sends none.
func NewAPIStore(baseURL, apiKey string, cacheTTL time.Duration, site func(context.Context) string) *APIStore {
	return &APIStore{
		baseURL:    baseURL,
		apiKey:     apiKey,
		site:       site,
		httpClient: &http.Client{Timeout: apiTimeout},
		cache:      cache.NewWithLimit(cacheTTL, apiCacheEntries),
		ttl:        cacheTTL,
		cityLists:  map[string]cityList{},
	}
}

var _ Store = (*APIStore)(nil)

func (s *APIStore) siteOf(ctx context.Context) string {
	if s.site == nil {
		return ""
	}
	return s.site(ctx)
}

// listingIDRe is a listing id: a directory id (digits) or a verified one
// ("lp-" and digits).
var listingIDRe = regexp.MustCompile(`^(?:lp-)?[0-9]+$`)

// IsListingID reports whether id is a listing id: digits, or "lp-" and
// digits (a verified localpages listing).
func IsListingID(id string) bool {
	return listingIDRe.MatchString(id)
}

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

// Search sends q as getBusinessList: the location as city and state (a city
// slug, as directory URLs have it, read as the getCities name), radius when
// q.RadiusMiles > 0, and a category group (q.AnyOf) as its categories,
// cut to the API's first 300. q.Group isn't sent (the API has no groups). A
// location the API doesn't know is an empty result, as is a page past the
// API's 1000.
func (s *APIStore) Search(ctx 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}
	if q.Location.IsZero() || page > apiMaxPage {
		return result, nil
	}
	params := url.Values{
		"action":   {"getBusinessList"},
		"city":     {s.cityName(ctx, q.Location)},
		"state":    {strings.ToUpper(q.Location.State)},
		"page":     {strconv.Itoa(page)},
		"per_page": {strconv.Itoa(pageSize)},
	}
	if keyword := strings.Join(strings.Fields(q.Keyword), " "); keyword != "" {
		params.Set("keyword", keyword)
	}
	if q.RadiusMiles > 0 {
		params.Set("radius", strconv.FormatFloat(q.RadiusMiles, 'f', -1, 64))
	}
	categories := apiCategories(q.AnyOf)

	var resp struct {
		Location struct {
			City string `json:"city"`
		} `json:"location"`
		Pagination struct {
			Total      int `json:"total"`
			TotalPages int `json:"total_pages"`
		} `json:"pagination"`
		Data []apiListing `json:"data"`
	}
	found, err := s.call(ctx, params, categories, &resp)
	if err != nil || !found {
		return result, err
	}
	result.CityName = resp.Location.City
	result.Total, result.TotalPages = resp.Pagination.Total, resp.Pagination.TotalPages
	for _, rec := range resp.Data {
		if l, ok := rec.listing(); ok {
			result.Listings = append(result.Listings, l)
		}
	}
	return result, nil
}

// apiCategories is a category group's terms as the API's categories: trimmed,
// without empty items and repeats, the first 300.
func apiCategories(terms []string) []string {
	out := []string{}
	seen := map[string]bool{}
	for _, term := range terms {
		term = strings.Join(strings.Fields(term), " ")
		if term == "" || seen[strings.ToLower(term)] {
			continue
		}
		seen[strings.ToLower(term)] = true
		out = append(out, term)
	}
	if len(out) > apiMaxCategories {
		log.Printf("[WARN] listings API: category group of %d terms cut to %d", len(out), apiMaxCategories)
		out = out[:apiMaxCategories]
	}
	return out
}

// Exists is a one-listing Search.
func (s *APIStore) Exists(ctx context.Context, q Query) (bool, error) {
	q.Page, q.PageSize = 1, 1
	result, err := s.Search(ctx, q)
	return result.Total > 0, err
}

// Get sends getBusinessDetails. An id that isn't a listing id, or one the
// API doesn't serve for the site, is not found.
func (s *APIStore) Get(ctx context.Context, id string) (Listing, bool, error) {
	if !IsListingID(id) {
		return Listing{}, false, nil
	}
	var resp struct {
		Data apiListing `json:"data"`
	}
	found, err := s.call(ctx, url.Values{"action": {"getBusinessDetails"}, "id": {id}}, nil, &resp)
	if err != nil || !found {
		return Listing{}, false, err
	}
	l, ok := resp.Data.listing()
	return l, ok, nil
}

// Nearby searches l's city for keyword, else for l's first category (the
// API's keyword matches category names too, and answers much faster than its
// categories), and returns up to n of the listings found, l left out. A
// listing without categories and no keyword has none.
func (s *APIStore) Nearby(ctx context.Context, l Listing, keyword string, n int) ([]Listing, error) {
	out := []Listing{}
	if keyword = strings.TrimSpace(keyword); keyword == "" && len(l.Categories) > 0 {
		keyword = l.Categories[0]
	}
	if keyword == "" || n < 1 {
		return out, nil
	}
	result, err := s.Search(ctx, Query{Keyword: keyword, Location: Location{City: l.City, State: l.State}, PageSize: n + 1})
	if err != nil {
		return nil, err
	}
	for _, other := range result.Listings {
		if other.ID != l.ID && len(out) < n {
			out = append(out, other)
		}
	}
	return out, nil
}

// States sends getStates: the states and dc, A to Z by code.
func (s *APIStore) States(ctx context.Context) ([]StateCount, error) {
	var resp struct {
		Data struct {
			States []struct {
				Code  string `json:"code"`
				Count int    `json:"count"`
			} `json:"states"`
		} `json:"data"`
	}
	if _, err := s.call(ctx, url.Values{"action": {"getStates"}}, nil, &resp); err != nil {
		return nil, err
	}
	out := []StateCount{}
	for _, st := range resp.Data.States {
		if code := strings.ToUpper(strings.TrimSpace(st.Code)); IsStateCode(code) && st.Count > 0 {
			out = append(out, StateCount{Code: code, Count: st.Count})
		}
	}
	sort.Slice(out, func(i, j int) bool { return out[i].Code < out[j].Code })
	return out, nil
}

// apiCityNameRe is a city name: letters, spaces, . ' ’ & and -, starting with
// a letter. getCities also has zips, street addresses, "<br>Newport Beach",
// "?Dallas" and "Lenexa, Kansas".
var apiCityNameRe = regexp.MustCompile(`^\pL[\pL .'’&-]*$`)

// Cities sends getCities for state, cleaned: names that aren't city names
// (see apiCityNameRe; double-decoded "Â"/"Ã" text too) and cities without
// coordinates are dropped, and of the spellings of one CitySlug ("St. Louis",
// "St Louis", "St.Louis") only the one with the most listings is kept. A to Z
// by name. Each site's and state's list is kept for the store's TTL.
func (s *APIStore) Cities(ctx context.Context, state string) ([]CityCount, error) {
	state = strings.ToUpper(strings.TrimSpace(state))
	if !IsStateCode(state) {
		return []CityCount{}, nil
	}
	key := s.siteOf(ctx) + "/" + state
	s.mu.Lock()
	list, ok := s.cityLists[key]
	s.mu.Unlock()
	if ok && time.Now().Before(list.expires) {
		return append([]CityCount{}, list.cities...), nil
	}

	var resp struct {
		Data struct {
			Cities []struct {
				Name  string   `json:"name"`
				Count int      `json:"count"`
				Lat   *float64 `json:"lat"`
				Lon   *float64 `json:"lon"`
			} `json:"cities"`
		} `json:"data"`
	}
	found, err := s.call(ctx, url.Values{"action": {"getCities"}, "state": {state}}, nil, &resp)
	if err != nil {
		return nil, err
	}
	bySlug := map[string]CityCount{}
	if found {
		for _, c := range resp.Data.Cities {
			name := strings.Join(strings.Fields(c.Name), " ")
			if !apiCityNameRe.MatchString(name) || strings.ContainsAny(name, "ÂÃ") || c.Lat == nil || c.Lon == nil || c.Count < 1 {
				continue
			}
			slug := CitySlug(name)
			if best, ok := bySlug[slug]; slug == "" || ok && best.Count >= c.Count {
				continue
			}
			bySlug[slug] = CityCount{Name: name, Slug: slug, State: state, Count: c.Count}
		}
	}
	cities := make([]CityCount, 0, len(bySlug))
	for _, c := range bySlug {
		cities = append(cities, c)
	}
	sort.Slice(cities, func(i, j int) bool {
		a, b := strings.ToLower(cities[i].Name), strings.ToLower(cities[j].Name)
		return a < b || a == b && cities[i].Name < cities[j].Name
	})
	s.mu.Lock()
	s.cityLists[key] = cityList{cities: cities, expires: time.Now().Add(s.ttl)}
	s.mu.Unlock()
	return append([]CityCount{}, cities...), nil
}

// cityName is the name the API knows loc's city by: the state's city with
// its CitySlug (so "los-angeles" is "Los Angeles"), else the city as given,
// hyphens as spaces.
func (s *APIStore) cityName(ctx context.Context, loc Location) string {
	if cities, err := s.Cities(ctx, loc.State); err == nil {
		slug := CitySlug(loc.City)
		for _, c := range cities {
			if c.Slug == slug {
				return c.Name
			}
		}
	}
	return cityWords(loc.City)
}

// ResolveLocation reads input as resolveLocation does: a zip is the city the
// API gives for it; a city with a state is the state's city of that slug (see
// Cities). A bare city (no state) isn't resolved: the API lists cities by
// state only.
func (s *APIStore) ResolveLocation(ctx context.Context, input string) (Location, bool, error) {
	return resolveLocation(ctx, input, s)
}

func (s *APIStore) zipLocation(ctx context.Context, zip string) (Location, bool, error) {
	var resp struct {
		Location struct {
			City  string `json:"city"`
			State string `json:"state"`
		} `json:"location"`
	}
	params := url.Values{"action": {"getBusinessList"}, "zip": {zip}, "page": {"1"}, "per_page": {"1"}}
	found, err := s.call(ctx, params, nil, &resp)
	l := Location{City: strings.Join(strings.Fields(resp.Location.City), " "), State: strings.ToUpper(resp.Location.State)}
	if err != nil || !found || l.IsZero() || !IsStateCode(l.State) {
		return Location{}, false, err
	}
	return l, true, nil
}

func (s *APIStore) stateLocation(ctx context.Context, city, state string) (Location, bool, error) {
	state = strings.TrimSpace(state)
	slug := CitySlug(city)
	if !IsStateCode(state) || slug == "" {
		return Location{}, false, nil
	}
	cities, err := s.Cities(ctx, state)
	if err != nil {
		return Location{}, false, err
	}
	for _, c := range cities {
		if c.Slug == slug {
			return Location{City: c.Name, State: c.State}, true, nil
		}
	}
	return Location{}, false, nil
}

func (s *APIStore) slugLocation(context.Context, string) (Location, bool, error) {
	return Location{}, false, nil
}

// call sends one API request, the site added, and decodes its answer into
// out: a GET of params, or a JSON POST when it has categories. found is false
// for a 404 (unknown location or listing). A cached answer is used while it
// lasts; a 404 is cached as nil.
func (s *APIStore) call(ctx context.Context, params url.Values, categories []string, out interface{}) (found bool, err error) {
	if site := s.siteOf(ctx); site != "" {
		params.Set("site", site)
	}
	key := params.Encode()
	if len(categories) > 0 {
		key += "&categories=" + url.QueryEscape(strings.Join(categories, "|"))
	}
	body, cached := s.cache.Get(key)
	if !cached {
		var status int
		body, status, err = s.fetch(ctx, params, categories)
		if err != nil {
			return false, err
		}
		if status == http.StatusNotFound {
			body = nil
		}
		s.cache.Set(key, body)
	}
	if body == nil {
		return false, nil
	}
	if err := json.Unmarshal(body, out); err != nil {
		return false, fmt.Errorf("listings API %s: decoding: %w", params.Get("action"), err)
	}
	return true, nil
}

// fetch makes the HTTP request of call. Any status but 200 and 404 is an
// error, with the API's message.
func (s *APIStore) fetch(ctx context.Context, params url.Values, categories []string) ([]byte, int, error) {
	var req *http.Request
	var err error
	if len(categories) == 0 {
		req, err = http.NewRequestWithContext(ctx, http.MethodGet, s.baseURL+"?"+params.Encode(), nil)
	} else {
		// The POST body takes every value as a string, categories as an array.
		payload := map[string]interface{}{"categories": categories}
		for name := range params {
			payload[name] = params.Get(name)
		}
		var data []byte
		if data, err = json.Marshal(payload); err != nil {
			return nil, 0, err
		}
		req, err = http.NewRequestWithContext(ctx, http.MethodPost, s.baseURL, bytes.NewReader(data))
		if err == nil {
			req.Header.Set("Content-Type", "application/json")
		}
	}
	if err != nil {
		return nil, 0, err
	}
	req.Header.Set("X-API-KEY", s.apiKey)
	req.Header.Set("Accept", "application/json")

	resp, err := s.httpClient.Do(req)
	if err != nil {
		return nil, 0, fmt.Errorf("listings API %s: %w", params.Get("action"), err)
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, 0, fmt.Errorf("listings API %s: reading: %w", params.Get("action"), err)
	}
	if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNotFound {
		var apiErr struct {
			Error string `json:"error"`
		}
		json.Unmarshal(body, &apiErr)
		return nil, 0, fmt.Errorf("listings API %s: status %d: %s", params.Get("action"), resp.StatusCode, apiErr.Error)
	}
	return body, resp.StatusCode, nil
}

// apiListing is a listing as the API returns it (search rows and details have
// the same shape).
type apiListing struct {
	ID             flexString  `json:"id"`
	Name           flexString  `json:"name"`
	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         []apiPhone  `json:"phones"`
	Website        flexString  `json:"website"`
	Categories     flexStrings `json:"categories"`
	Description    flexString  `json:"description"`
	Hours          []apiHour   `json:"hours"`
	Services       flexString  `json:"services"`
	Products       flexString  `json:"products"`
	PaymentOptions flexStrings `json:"payment_options"`
	SpecialOffer   flexString  `json:"special_offer"`
	SpecialURL     flexString  `json:"special_offer_url"`
	Images         flexStrings `json:"images"`
	Videos         flexStrings `json:"videos"`
	YextID         flexString  `json:"yext_id"`
	Source         flexString  `json:"source"`
}

type apiPhone struct {
	Number flexString `json:"number"`
	Label  flexString `json:"label"`
}

// apiHour is one day: open and close as "07:30", or closed.
type apiHour struct {
	Day    flexString `json:"day"`
	Open   flexString `json:"open"`
	Close  flexString `json:"close"`
	Closed bool       `json:"closed"`
}

// listing turns an API record into a Listing, cleaned as normalise cleans an
// import record. Hours are lines like the import's ("Monday : 7:30 AM -
// 4:00 PM", "Sunday : Closed"). ok is false without a listing id, name, city
// or state code.
func (rec apiListing) listing() (Listing, bool) {
	l := Listing{
		ID:             clean(rec.ID),
		Name:           apiText(string(rec.Name)),
		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:         []Phone{},
		Website:        website(clean(rec.Website)),
		Categories:     cleanItems(rec.Categories),
		Description:    strings.Join(textLines(unescapeQuotes(string(rec.Description))), "\n"),
		Hours:          apiHours(rec.Hours),
		Services:       apiText(string(rec.Services)),
		Products:       apiText(string(rec.Products)),
		PaymentOptions: cleanItems(rec.PaymentOptions),
		Images:         images(rec.Images),
		Videos:         []string{},
		YextID:         clean(rec.YextID),
		Source:         clean(rec.Source),
	}
	for _, p := range rec.Phones {
		if phone, ok := formatPhone(clean(p.Number), clean(p.Label)); ok {
			l.Phones = append(l.Phones, phone)
		}
	}
	for _, id := range rec.Videos {
		if id = strings.TrimSpace(id); youTubeIDRe.MatchString(id) {
			l.Videos = append(l.Videos, id)
		}
	}
	if text, link := apiText(string(rec.SpecialOffer)), webURL(clean(rec.SpecialURL)); text != "" || link != "" {
		l.SpecialOffer = &SpecialOffer{Text: text, URL: link}
	}
	if !IsListingID(l.ID) || l.Name == "" || CitySlug(l.City) == "" || !IsStateCode(l.State) {
		return Listing{}, false
	}
	l.URL = ListingURL(l.State, l.City, l.ID, l.Name)
	return l, true
}

// apiText is plain text with the API's backslash-escaped quotes ("Women\'s")
// unescaped.
func apiText(s string) string {
	return plainText(unescapeQuotes(s))
}

func unescapeQuotes(s string) string {
	return strings.NewReplacer(`\'`, "'", `\"`, `"`).Replace(s)
}

// cleanItems trims each item, dropping empty ones.
func cleanItems(in flexStrings) []string {
	out := []string{}
	for _, item := range in {
		if item = clean(flexString(item)); item != "" {
			out = append(out, item)
		}
	}
	return out
}

// apiHours reads the days as hours lines; a day without a valid open and
// close time (and not closed) is dropped.
func apiHours(days []apiHour) []string {
	out := []string{}
	for _, h := range days {
		day := clean(h.Day)
		if day == "" {
			continue
		}
		if h.Closed {
			out = append(out, day+" : Closed")
			continue
		}
		open, okOpen := clockTime(clean(h.Open))
		shut, okClose := clockTime(clean(h.Close))
		if okOpen && okClose {
			out = append(out, day+" : "+open+" - "+shut)
		}
	}
	return out
}

// clockTime reads "07:30" (24-hour) as "7:30 AM".
func clockTime(s string) (string, bool) {
	t, err := time.Parse("15:04", s)
	if err != nil {
		return "", false
	}
	return t.Format("3:04 PM"), true
}
