package listings

import (
	"context"
	"net/url"
	"strings"
)

// stateCodes are the US state codes a directory URL can start with: the 50
// states and dc.
var stateCodes = map[string]bool{
	"al": true, "ak": true, "az": true, "ar": true, "ca": true, "co": true, "ct": true, "de": true,
	"dc": true, "fl": true, "ga": true, "hi": true, "id": true, "il": true, "in": true, "ia": true,
	"ks": true, "ky": true, "la": true, "me": true, "md": true, "ma": true, "mi": true, "mn": true,
	"ms": true, "mo": true, "mt": true, "ne": true, "nv": true, "nh": true, "nj": true, "nm": true,
	"ny": true, "nc": true, "nd": true, "oh": true, "ok": true, "or": true, "pa": true, "ri": true,
	"sc": true, "sd": true, "tn": true, "tx": true, "ut": true, "vt": true, "va": true, "wa": true,
	"wv": true, "wi": true, "wy": true,
}

// IsStateCode reports whether s is a US state code (or dc), in any case.
func IsStateCode(s string) bool {
	return stateCodes[strings.ToLower(s)]
}

// Location is a city and its state code.
type Location struct {
	City  string
	State string
}

// ParseLocation reads "City, ST" (the comma optional, "Los Angeles CA"), in
// any case. ok is false without a city or a valid state code.
func ParseLocation(s string) (Location, bool) {
	s = strings.TrimSpace(s)
	var city, state string
	if i := strings.LastIndex(s, ","); i >= 0 {
		city, state = s[:i], s[i+1:]
	} else if i := strings.LastIndexAny(s, " \t"); i >= 0 {
		city, state = s[:i], s[i+1:]
	}
	city, state = strings.Join(strings.Fields(city), " "), strings.TrimSpace(state)
	if city == "" || !IsStateCode(state) {
		return Location{}, false
	}
	return Location{City: city, State: strings.ToUpper(state)}, true
}

// locationLookup is what resolveLocation asks a store: the city of a zip, a
// city in a state (city as typed, state a code in any case) and a city by its
// CitySlug in any state, spelled as the store spells it; ok is false when the
// store has none.
type locationLookup interface {
	zipLocation(ctx context.Context, zip string) (Location, bool, error)
	stateLocation(ctx context.Context, city, state string) (Location, bool, error)
	slugLocation(ctx context.Context, slug string) (Location, bool, error)
}

// resolveLocation tries, in order: a 5-digit zip (or zip+4); "City, ST" then
// "ST, City" when the input has a comma; "City ST"; a bare city. A trailing
// country or zip after the city and state is dropped (trimLocationSuffixes).
// The forms with a state give the city as the store spells it, or as typed
// when the store has no such city in that state (a valid "City, ST" still
// resolves, as ParseLocation reads it); a zip or bare city must be the
// store's. Case, "+", %-escapes, hyphens for spaces and trailing "/" are
// tolerated.
func resolveLocation(ctx context.Context, input string, look locationLookup) (Location, bool, error) {
	in := input
	if unescaped, err := url.QueryUnescape(in); err == nil {
		in = unescaped
	} else {
		in = strings.ReplaceAll(in, "+", " ")
	}
	in = trimLocationSuffixes(strings.TrimSpace(strings.TrimRight(strings.TrimSpace(in), "/")))
	if in == "" {
		return Location{}, false, nil
	}
	if zip := zip5(in); zip != "" && len(in) <= 10 {
		return look.zipLocation(ctx, zip)
	}
	if a, b, ok := strings.Cut(in, ","); ok {
		pairs := [][2]string{{a, b}, {b, a}}
		for _, pair := range pairs {
			if l, ok, err := look.stateLocation(ctx, pair[0], pair[1]); err != nil || ok {
				return l, ok, err
			}
		}
		for _, pair := range pairs {
			if city := cityWords(pair[0]); city != "" && IsStateCode(strings.TrimSpace(pair[1])) && !IsStateCode(city) {
				return Location{City: city, State: strings.ToUpper(strings.TrimSpace(pair[1]))}, true, nil
			}
		}
		return Location{}, false, nil
	}
	words := strings.Fields(strings.ReplaceAll(in, "-", " "))
	if n := len(words); n > 1 && IsStateCode(words[n-1]) {
		city := strings.Join(words[:n-1], " ")
		if l, ok, err := look.stateLocation(ctx, city, words[n-1]); err != nil || ok {
			return l, ok, err
		}
		if l, ok, err := look.slugLocation(ctx, CitySlug(in)); err != nil || ok {
			return l, ok, err
		}
		return Location{City: city, State: strings.ToUpper(words[n-1])}, true, nil
	}
	return look.slugLocation(ctx, CitySlug(in))
}

// IsZero reports whether l has no city.
func (l Location) IsZero() bool { return l.City == "" }

// Label is "City, ST".
func (l Location) Label() string {
	if l.IsZero() {
		return ""
	}
	return l.City + ", " + strings.ToUpper(l.State)
}

// Path is the city page URL, /{st}/{citySlug}.
func (l Location) Path() string {
	if l.IsZero() {
		return ""
	}
	return "/" + strings.ToLower(l.State) + "/" + CitySlug(l.City)
}

// key is how the store matches a location: "los-angeles" and "Los Angeles"
// are the same city.
func (l Location) key() string {
	return strings.ToLower(l.State) + "/" + CitySlug(l.City)
}

// CitySlug is a city's URL segment: lowercase, every run of characters other
// than a-z and 0-9 a single "-", trimmed ("Los Angeles" → "los-angeles").
func CitySlug(city string) string {
	return dashed(strings.ToLower(city))
}

// NameSlug is a listing name's URL slug: lowercase, "&" spelled "and",
// apostrophes dropped, then as CitySlug ("Children's Dentistry & Ortho" →
// "childrens-dentistry-and-ortho").
func NameSlug(name string) string {
	name = strings.ToLower(name)
	name = strings.NewReplacer("&", "and", "'", "", "’", "").Replace(name)
	return dashed(name)
}

// dashed turns every run of characters other than a-z and 0-9 into one "-",
// trimming them at both ends.
func dashed(s string) string {
	var b strings.Builder
	b.Grow(len(s))
	pending := false
	for _, r := range s {
		if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' {
			if pending && b.Len() > 0 {
				b.WriteByte('-')
			}
			pending = false
			b.WriteRune(r)
			continue
		}
		pending = true
	}
	return b.String()
}

// ListingURL is a listing's canonical path, /{st}/{citySlug}/{id}-{nameSlug}
// (just /{st}/{citySlug}/{id} when the name has no slug).
func ListingURL(state, city, id, name string) string {
	segment := id
	if slug := NameSlug(name); slug != "" {
		segment += "-" + slug
	}
	return Location{City: city, State: state}.Path() + "/" + segment
}
