// Package dict loads the English test dictionary as a DAWG from the committed
// dawg/en_sowpods.dawg fixture, for the cmd/stress benchmark. The dictionary build
// pipeline (word-list parsing and DAWG construction from sources) now lives in the
// separate scrabble-dictionary repository; this package only loads the committed
// artifact. Paths are resolved relative to the repository root so it works both from
// the repo root (commands) and from a package directory (tests).
package dict

import (
	"os"
	"path/filepath"

	dawg "github.com/iliadenisov/dafsa"

	"gitea.iliadenisov.ru/developer/scrabble-solver/dictdawg"
)

func exists(p string) bool { _, err := os.Stat(p); return err == nil }

// Root returns the repository root by walking up from the working directory to the
// directory containing go.mod, or "." if none is found.
func Root() string {
	dir, err := os.Getwd()
	if err != nil {
		return "."
	}
	for {
		if exists(filepath.Join(dir, "go.mod")) {
			return dir
		}
		parent := filepath.Dir(dir)
		if parent == dir {
			return "."
		}
		dir = parent
	}
}

// DAWGCache locates the committed English DAWG, relative to the repository root.
func DAWGCache() string { return filepath.Join(Root(), "dawg", "en_sowpods.dawg") }

// EnglishAvailable reports whether the committed English DAWG is present.
func EnglishAvailable() bool { return exists(DAWGCache()) }

// EnglishDAWG loads the committed English DAWG.
func EnglishDAWG() (dawg.Finder, error) { return dictdawg.Load(DAWGCache()) }
