package main

import (
	"context"
	"encoding/json"
	"flag"
	"log"
	"os"
	"os/signal"
	"syscall"

	"git.gensokyo.uk/yonah/monstersirenfetch"
)

func main() {
	log.SetFlags(0)
	log.SetPrefix("msrfetch: ")
	flag.Parse()

	if flag.NArg() < 1 {
		log.Fatal("no subcommand specified")
	}

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	switch flag.Args()[0] {
	case "enrich":
		mustEnrich(ctx)

	case "fetch":
		mustFetch(ctx)

	default:
		log.Fatalf("%q is not a valid command", flag.Args()[0])
	}

}

func mustWriteJSON(pathname string, v any) {
	if w, err := os.Create(pathname); err != nil {
		log.Fatal(err)
	} else if err = monstersirenfetch.NewEncoder(w).Encode(v); err != nil {
		log.Fatal(err)
	} else if err = w.Close(); err != nil {
		log.Fatal(err)
	}
}

func mustReadJSON(pathname string, v any) {
	if r, err := os.OpenFile(pathname, os.O_RDONLY, 0); err != nil {
		log.Fatal(err)
	} else if err = json.NewDecoder(r).Decode(v); err != nil {
		log.Fatal(err)
	} else if err = r.Close(); err != nil {
		log.Fatal(err)
	}
}
