// Package places serves the place text of the directory sites' state and city
// pages: Wikipedia extracts, one JSON file per state ({st}.json, lowercase
// code), loaded once at startup:
//
//	{ "state": {"code": "VA", "name": "Virginia", "title": "Virginia", "sourceUrl": "https://en.wikipedia.org/wiki/Virginia",
//	            "intro": ["..."], "sections": [{"heading": "History", "paragraphs": ["..."]}]},
//	  "cities": {"ashburn": {"name": "Ashburn", "title": "Ashburn, Virginia", "sourceUrl": "...", "intro": ["..."]}} }
package places

import (
	"encoding/json"
	"errors"
	"io/fs"
	"log"
	"os"
	"path/filepath"
	"strings"

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

// Section is a headed part of a state's article.
type Section struct {
	Heading    string   `json:"heading"`
	Paragraphs []string `json:"paragraphs"`
}

// Place is the text of a state or a city.
type Place struct {
	Name      string    `json:"name"`
	Title     string    `json:"title"`
	SourceURL string    `json:"sourceUrl"`
	Intro     []string  `json:"intro"`
	Sections  []Section `json:"sections"`
}

// stateFile is one {st}.json file.
type stateFile struct {
	State  Place            `json:"state"`
	Cities map[string]Place `json:"cities"`
}

// Store holds the place text of every state file loaded. The zero value (and
// a nil *Store) has none.
type Store struct {
	states map[string]stateFile // by lowercase state code
}

// Load reads every {st}.json in dir. A missing dir gives an empty store, so the
// service runs without place text; a file that doesn't parse, or isn't named
// after a state code, is logged and skipped.
func Load(dir string) (*Store, error) {
	store := &Store{states: map[string]stateFile{}}
	entries, err := os.ReadDir(dir)
	if errors.Is(err, fs.ErrNotExist) {
		return store, nil
	}
	if err != nil {
		return store, err
	}
	for _, entry := range entries {
		code, ok := strings.CutSuffix(entry.Name(), ".json")
		if entry.IsDir() || !ok {
			continue
		}
		if code != strings.ToLower(code) || !listings.IsStateCode(code) {
			log.Printf("[WARN] places: skipping %s (not {st}.json)", entry.Name())
			continue
		}
		data, err := os.ReadFile(filepath.Join(dir, entry.Name()))
		if err != nil {
			log.Printf("[WARN] places: skipping %s: %v", entry.Name(), err)
			continue
		}
		var file stateFile
		if err := json.Unmarshal(data, &file); err != nil {
			log.Printf("[WARN] places: skipping %s: %v", entry.Name(), err)
			continue
		}
		// City keys in the CitySlug form, so "Los Angeles" and "los-angeles" are one.
		cities := make(map[string]Place, len(file.Cities))
		for key, city := range file.Cities {
			if slug := listings.CitySlug(key); slug != "" {
				cities[slug] = city
			}
		}
		file.Cities = cities
		store.states[code] = file
	}
	return store, nil
}

// State returns a state's text (code in any case); ok is false without one.
func (s *Store) State(code string) (Place, bool) {
	if s == nil {
		return Place{}, false
	}
	file, ok := s.states[strings.ToLower(code)]
	return file.State, ok && len(file.State.Intro) > 0
}

// City returns a city's text, by state code (any case) and city name or slug;
// ok is false without one.
func (s *Store) City(state, city string) (Place, bool) {
	if s == nil {
		return Place{}, false
	}
	place, ok := s.states[strings.ToLower(state)].Cities[listings.CitySlug(city)]
	return place, ok && len(place.Intro) > 0
}

// stateNames are the names of the US state codes (and dc).
var stateNames = map[string]string{
	"al": "Alabama", "ak": "Alaska", "az": "Arizona", "ar": "Arkansas", "ca": "California", "co": "Colorado",
	"ct": "Connecticut", "de": "Delaware", "dc": "District of Columbia", "fl": "Florida", "ga": "Georgia",
	"hi": "Hawaii", "id": "Idaho", "il": "Illinois", "in": "Indiana", "ia": "Iowa", "ks": "Kansas",
	"ky": "Kentucky", "la": "Louisiana", "me": "Maine", "md": "Maryland", "ma": "Massachusetts",
	"mi": "Michigan", "mn": "Minnesota", "ms": "Mississippi", "mo": "Missouri", "mt": "Montana",
	"ne": "Nebraska", "nv": "Nevada", "nh": "New Hampshire", "nj": "New Jersey", "nm": "New Mexico",
	"ny": "New York", "nc": "North Carolina", "nd": "North Dakota", "oh": "Ohio", "ok": "Oklahoma",
	"or": "Oregon", "pa": "Pennsylvania", "ri": "Rhode Island", "sc": "South Carolina", "sd": "South Dakota",
	"tn": "Tennessee", "tx": "Texas", "ut": "Utah", "vt": "Vermont", "va": "Virginia", "wa": "Washington",
	"wv": "West Virginia", "wi": "Wisconsin", "wy": "Wyoming",
}

// StateName returns the name of a state code in any case ("va" → "Virginia"),
// or "" for anything else.
func StateName(code string) string {
	return stateNames[strings.ToLower(code)]
}
