package staticserver

import (
	"errors"
	"fmt"
	"net"
	"net/http"
	"os"
	"path/filepath"
)

func Serve(dir string, host string, port string) error {
	info, err := os.Stat(dir)
	if err != nil {
		return err
	}
	if !info.IsDir() {
		return fmt.Errorf("static path %s is not a directory", dir)
	}

	addr := net.JoinHostPort(host, port)
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path := filepath.Clean("/" + r.URL.Path)
		if path == "/" {
			path = "/index.html"
		}

		fullPath := filepath.Join(dir, filepath.FromSlash(path))
		if info, err := os.Stat(fullPath); err == nil && info.IsDir() {
			fullPath = filepath.Join(fullPath, "index.html")
		} else if errors.Is(err, os.ErrNotExist) && filepath.Ext(fullPath) == "" {
			fullPath = filepath.Join(dir, filepath.FromSlash(path), "index.html")
		}

		if _, err := os.Stat(fullPath); err != nil {
			http.NotFound(w, r)
			return
		}

		http.ServeFile(w, r, fullPath)
	})

	fmt.Printf("serving %s at http://%s\n", dir, addr)
	return http.ListenAndServe(addr, handler)
}
