package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"git.max-richter.dev/max/marka/server/internal/adapters"
	"git.max-richter.dev/max/marka/server/internal/handler"
)

var commit = "unknown"

type multi []string

func (m *multi) String() string { return strings.Join(*m, ",") }
func (m *multi) Set(v string) error {
	*m = append(*m, v)
	return nil
}

func main() {
	log.Printf("marka-server, commit=%s", commit)
	var roots multi
	flag.Var(&roots, "root", "repeatable; specify multiple -root flags")
	addr := flag.String("addr", ":8080", "listen address")
	playgroundRoot := flag.String("playground-root", "/app/playground", "path to playground build directory")
	flag.Parse()

	if *playgroundRoot != "" {
		absPlaygroundRoot, err := filepath.Abs(*playgroundRoot)
		must(err)
		info, err := os.Stat(absPlaygroundRoot)
		if err == nil {
			if !info.IsDir() {
				log.Fatalf("playground-root %s is not a directory", *playgroundRoot)
			}
			log.Printf("serving playground from %s", absPlaygroundRoot)
			http.Handle("/_playground/", http.StripPrefix("/_playground/", http.FileServer(http.Dir(absPlaygroundRoot))))
		}
	}

	if len(roots) == 0 {
		log.Fatal("at least one -root flag must be specified")
	}

	absRoots := make([]string, len(roots))
	for i, r := range roots {
		abs, err := filepath.Abs(r)
		must(err)
		info, err := os.Stat(abs)
		must(err)
		if !info.IsDir() {
			log.Fatalf("root %s is not a directory", r)
		}
		absRoots[i] = abs
	}

	fsAdapter, err := adapters.NewLocalFsAdapter(absRoots)
	must(err)

	apiKey := os.Getenv("MARKA_API_KEY")
	fmt.Println(apiKey)
	http.Handle("/", handler.NewHandler(fsAdapter, apiKey))

	log.Printf("listening on %s, roots=%s", *addr, strings.Join(absRoots, ", "))
	log.Fatal(http.ListenAndServe(*addr, nil))
}

func must(err error) {
	if err != nil {
		log.Fatal(err)
	}
}
