package main

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

	_ "github.com/mattn/go-sqlite3"
)

func main() {
	initDBConnection()
	defer db.Close()

	syncResults()

	// Handle API routes
	http.HandleFunc("/api/simulations", getSimulations)
	http.HandleFunc("/api/simulations/create", createSimulation)
	http.HandleFunc("/api/simulations/", getSimulationDetails)

	// Serve the static files from results directory
	resultsDir := "../results"
	fsResults := http.FileServer(http.Dir(resultsDir))
	http.Handle("/results/", http.StripPrefix("/results/", fsResults))

	// Serve the static frontend with SPA fallback
	frontendDir := "../build"
	fsFrontend := http.FileServer(http.Dir(frontendDir))
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		path := filepath.Join(frontendDir, r.URL.Path)
		_, err := os.Stat(path)
		if os.IsNotExist(err) {
			http.ServeFile(w, r, filepath.Join(frontendDir, "index.html"))
			return
		}
		fsFrontend.ServeHTTP(w, r)
	})

	fmt.Println("Server listening on port 5173")

	// Wrap the default ServeMux with our logging middleware
	loggedMux := loggingMiddleware(http.DefaultServeMux)
	log.Fatal(http.ListenAndServe("0.0.0.0:5173", loggedMux))
}

func loggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if strings.HasPrefix(r.URL.Path, "/api/") {
			log.Printf("[%s] %s %s", r.RemoteAddr, r.Method, r.URL.Path)
		}
		next.ServeHTTP(w, r)
	})
}
