package main

import (
	"embed"
	"encoding/json"
	"html/template"
	"log/slog"
	"mime"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

//go:embed templates/*.html static/*
var appFS embed.FS

type App struct {
	Log       *slog.Logger
	Templates *template.Template
	BaseURL   string
	Cache     *feedCache
	Images    *imageCache
	renderSem chan struct{}
}

type templateItem struct {
	Title         string
	Link          string
	Author        string
	FormattedDate string
}

type feedRef struct {
	Name string
	URL  string
}

type indexPageData struct {
	BaseURL         string
	Items           []templateItem
	FeedURLs        []feedRef
	Error           string
	MetaTitle       string
	MetaDescription string
	CanonicalURL    string
	OGImage         string
}

func (a *App) routes() *http.ServeMux {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /", a.indexHandler)
	mux.HandleFunc("GET /privacy", a.privacyHandler)
	mux.HandleFunc("GET /og.png", a.ogImageHandler)
	mux.HandleFunc("GET /api/resolve", a.resolveHandler)
	mux.HandleFunc("GET /static/", embeddedHandler(appFS, "static"))
	return mux
}

// limitInFlight caps concurrent in-flight requests. Under a traffic spike,
// excess requests get an immediate 503 rather than piling up goroutines and
// outbound connections that would exhaust file descriptors. Static asset
// requests are cheap (served from memory) and bypass the limiter.
func limitInFlight(next http.Handler, max int) http.Handler {
	sem := make(chan struct{}, max)
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if strings.HasPrefix(r.URL.Path, "/static/") {
			next.ServeHTTP(w, r)
			return
		}
		select {
		case sem <- struct{}{}:
			defer func() { <-sem }()
			next.ServeHTTP(w, r)
		default:
			http.Error(w, "server busy", http.StatusServiceUnavailable)
		}
	})
}

// embeddedHandler serves files from an embed.FS under the given URL prefix.
func embeddedHandler(fs embed.FS, prefix string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		name := strings.TrimPrefix(r.URL.Path, "/"+prefix+"/")
		path := filepath.ToSlash(filepath.Join(prefix, name))
		data, err := fs.ReadFile(path)
		if err != nil {
			http.NotFound(w, r)
			return
		}
		if ct := mime.TypeByExtension(filepath.Ext(path)); ct != "" {
			w.Header().Set("Content-Type", ct)
		}
		_, _ = w.Write(data)
	}
}

// render executes a named template into w. Errors are logged and surfaced as HTTP 500.
func render(t *template.Template, w http.ResponseWriter, name string, data any, log *slog.Logger) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := t.ExecuteTemplate(w, name, data); err != nil {
		if log != nil {
			log.Error("template render failed", "name", name, "err", err)
		}
		http.Error(w, "template error", http.StatusInternalServerError)
	}
}

// writeJSON writes data as JSON with the given status code.
func writeJSON(w http.ResponseWriter, status int, data any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(data)
}

// writeError writes a JSON error response of the form {"error": msg}.
func writeError(w http.ResponseWriter, status int, msg string) {
	writeJSON(w, status, map[string]any{"error": msg})
}

// getenv returns the trimmed value of key or fallback when unset/blank.
func getenv(key, fallback string) string {
	if v := strings.TrimSpace(os.Getenv(key)); v != "" {
		return v
	}
	return fallback
}

// loadDotEnv reads KEY=VALUE pairs from a .env file in the working directory
// and sets them as environment variables, without overriding vars already set.
func loadDotEnv(path string) {
	data, err := os.ReadFile(path)
	if err != nil {
		return
	}
	for line := range strings.SplitSeq(string(data), "\n") {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		key, value, ok := strings.Cut(line, "=")
		if !ok {
			continue
		}
		key = strings.TrimSpace(key)
		value = strings.TrimSpace(value)
		value = strings.Trim(value, `"'`)
		if key == "" {
			continue
		}
		if _, exists := os.LookupEnv(key); !exists {
			os.Setenv(key, value)
		}
	}
}
