package main

import (
	"caltrack/ai"
	"caltrack/api"
	cfgpkg "caltrack/config"
	"caltrack/db"
	"embed"
	"fmt"
	"io/fs"
	"log"
	"net/http"
)

//go:embed web
var webFS embed.FS

func main() {
	cfg, err := cfgpkg.Load()
	if err != nil {
		log.Printf("Warning: could not load config: %v (using defaults)", err)
	}

	database, err := db.New()
	if err != nil {
		log.Fatalf("Failed to open database: %v", err)
	}
	defer database.Close()

	aiClient := ai.New(&cfg, database)

	handler := api.New(database, aiClient, &cfg)

	mux := http.NewServeMux()
	handler.RegisterRoutes(mux)

	// Serve embedded web files
	webContent, err := fs.Sub(webFS, "web")
	if err != nil {
		log.Fatalf("Failed to setup web filesystem: %v", err)
	}

	mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/" {
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
			data, _ := fs.ReadFile(webContent, "index.html")
			w.Write(data)
			return
		}
		http.FileServer(http.FS(webContent)).ServeHTTP(w, r)
	})

	addr := cfg.ListenAddr
	if addr == "" {
		addr = ":8080"
	}

	fmt.Printf("CalTrack running at http://localhost%s\n", addr)
	if err := http.ListenAndServe(addr, mux); err != nil {
		log.Fatalf("Server error: %v", err)
	}
}
