package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/ashie/gosearch/internal/config"
	"github.com/ashie/gosearch/internal/httpapi"
	"github.com/ashie/gosearch/internal/search"
)

func main() {
	configPath := flag.String("config", "config.toml", "path to config.toml")
	flag.Parse()

	cfg, err := config.Load(*configPath)
	if err != nil {
		log.Fatalf("failed to load config: %v", err)
	}

	// Seed env vars from config so existing engine/factory/planner code
	// picks them up without changes. The config layer is the single source
	// of truth; env vars remain as overrides via applyEnvOverrides.
	if len(cfg.Engines.LocalPorted) > 0 {
		os.Setenv("LOCAL_PORTED_ENGINES", cfg.LocalPortedCSV())
	}
	if cfg.Engines.Brave.APIKey != "" {
		os.Setenv("BRAVE_API_KEY", cfg.Engines.Brave.APIKey)
	}
	if cfg.Engines.Brave.AccessToken != "" {
		os.Setenv("BRAVE_ACCESS_TOKEN", cfg.Engines.Brave.AccessToken)
	}

	svc := search.NewService(search.ServiceConfig{
		UpstreamURL: cfg.Upstream.URL,
		HTTPTimeout: cfg.HTTPTimeout(),
	})

	h := httpapi.NewHandler(svc)

	mux := http.NewServeMux()
	mux.HandleFunc("/healthz", h.Healthz)
	mux.HandleFunc("/search", h.Search)

	addr := fmt.Sprintf(":%d", cfg.Server.Port)
	log.Printf("searxng-go listening on %s", addr)
	log.Fatal(http.ListenAndServe(addr, mux))
}
