package main

import (
	"fmt"
	"log"
	"log/slog"
	"os"
	"strings"
	"training/terms"
)

func main() {
	var loggingLevel = new(slog.LevelVar)

	wd, err := os.Getwd()
	if err != nil {
		log.Fatal("unable to determine working directory")
	}

	replacer := func(groups []string, a slog.Attr) slog.Attr {
		if a.Key == slog.SourceKey {
			source := a.Value.Any().(*slog.Source)
			if file, ok := strings.CutPrefix(source.File, wd); ok {
				source.File = file
			}
		}
		return a
	}

	options := &slog.HandlerOptions{
		Level:       loggingLevel,
		ReplaceAttr: replacer,
	}

	if os.Getenv("loglevel") == "debug" {
		loggingLevel.Set(slog.LevelDebug)
		options.AddSource = true
	}

	logger := slog.New(slog.NewJSONHandler(os.Stderr, options))

	slog.SetDefault(logger)

	filename := os.Args[1]
	in, err := os.Open(filename)
	if err != nil {
		slog.Error("Unable to open file", "err", err)
		os.Exit(1)
	}
	defer in.Close()

	slog.Info("processing terms")
	tf, err := terms.Frequency(logger, in)
	if err != nil {
		slog.Error("Error indexing", "err", err)
	}
	if err := in.Close(); err != nil {
		slog.Error("Error closing file", "err", err)
	}

	// write words to file
	out, err := os.Create("terms.txt")
	if err != nil {
		slog.Error("Error creating file", "err", err)
	}
	defer out.Close()
	fmt.Fprintln(out, "Index:")

	for k, v := range tf {
		fmt.Fprintln(out, k, ": ", v)
	}
	if err := out.Close(); err != nil {
		slog.Error("Error closing file", "err", err)
	}
}
