package server

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"sort"
	"strings"
	"time"

	"mkblog/internal/site"
)

type ServeOptions struct {
	Port  int
	Watch bool
	Build site.BuildOptions
}

func Serve(opts ServeOptions) error {
	if _, err := site.Build(opts.Build); err != nil {
		return err
	}

	if opts.Watch {
		go watchAndRebuild(opts.Build)
	}

	addr := fmt.Sprintf(":%d", opts.Port)
	log.Printf("serving %s on http://localhost%s", opts.Build.OutDir, addr)
	return http.ListenAndServe(addr, newFileHandler(opts.Build.OutDir))
}

func newFileHandler(outDir string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodGet && r.Method != http.MethodHead {
			http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
			return
		}

		requestPath := r.URL.Path
		if requestPath == "" {
			requestPath = "/"
		}
		cleanPath := path.Clean("/" + strings.TrimPrefix(requestPath, "/"))
		targetPath := filepath.Join(outDir, filepath.FromSlash(strings.TrimPrefix(cleanPath, "/")))

		st, err := os.Stat(targetPath)
		switch {
		case err == nil:
			if st.IsDir() {
				indexPath := filepath.Join(targetPath, "index.html")
				_, indexErr := os.Stat(indexPath)
				if indexErr == nil {
					if !strings.HasSuffix(requestPath, "/") {
						location := cleanPath + "/"
						if r.URL.RawQuery != "" {
							location += "?" + r.URL.RawQuery
						}
						http.Redirect(w, r, location, http.StatusMovedPermanently)
						return
					}
					http.ServeFile(w, r, indexPath)
					return
				}
				if os.IsNotExist(indexErr) {
					serveNotFound(w, r, outDir, site.NotFoundDenied)
					return
				}
				http.Error(w, "internal server error", http.StatusInternalServerError)
				return
			}
			http.ServeFile(w, r, targetPath)
			return
		case os.IsNotExist(err):
			serveNotFound(w, r, outDir, site.NotFoundNoSuch)
			return
		default:
			http.Error(w, "internal server error", http.StatusInternalServerError)
			return
		}
	})
}

func serveNotFound(w http.ResponseWriter, r *http.Request, outDir, notFoundError string) {
	page, err := os.ReadFile(filepath.Join(outDir, "404.html"))
	if err != nil {
		http.NotFound(w, r)
		return
	}

	displayPath := formatNotFoundPath(r.URL.EscapedPath())
	rendered := site.Render404HTML(page, displayPath, notFoundError)

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(http.StatusNotFound)
	if r.Method != http.MethodHead {
		_, _ = io.WriteString(w, string(rendered))
	}
}

func formatNotFoundPath(rawPath string) string {
	if rawPath == "" {
		return "/"
	}
	decoded, err := url.PathUnescape(rawPath)
	if err != nil {
		decoded = rawPath
	}
	if decoded == "/" {
		return "/"
	}
	trimmed := strings.TrimLeft(decoded, "/")
	if trimmed == "" {
		return "/"
	}
	return trimmed
}

func watchAndRebuild(buildOpts site.BuildOptions) {
	paths, err := watchPaths(buildOpts)
	if err != nil {
		log.Printf("watch setup error: %v", err)
		return
	}

	state, err := scanMtimes(paths...)
	if err != nil {
		log.Printf("watch scan error: %v", err)
		return
	}
	log.Printf("watch initialized: tracking %d files", len(state))

	watcher, err := newNativeWatcher(paths)
	if err != nil {
		log.Printf("watch native setup failed, falling back to polling: %v", err)
		watchAndRebuildPolling(buildOpts, state)
		return
	}
	defer watcher.Close()

	for {
		if !waitForWatchBurst(watcher.Events(), 150*time.Millisecond) {
			return
		}
		next, ok := rebuildOnWatchChange(buildOpts, watcher, state)
		if !ok {
			return
		}
		state = next
	}
}

type watchChange struct {
	Kind string
	Path string
}

func diffWatchState(prev, next map[string]time.Time) []watchChange {
	changes := make([]watchChange, 0)
	for path, prevTime := range prev {
		nextTime, ok := next[path]
		if !ok {
			changes = append(changes, watchChange{Kind: "removed", Path: path})
			continue
		}
		if !prevTime.Equal(nextTime) {
			changes = append(changes, watchChange{Kind: "modified", Path: path})
		}
	}
	for path := range next {
		if _, ok := prev[path]; !ok {
			changes = append(changes, watchChange{Kind: "added", Path: path})
		}
	}
	sort.Slice(changes, func(i, j int) bool {
		if changes[i].Path == changes[j].Path {
			return changes[i].Kind < changes[j].Kind
		}
		return changes[i].Path < changes[j].Path
	})
	return changes
}

func summarizeWatchChanges(changes []watchChange, limit int) string {
	if len(changes) == 0 {
		return "no file changes"
	}
	if limit <= 0 || limit > len(changes) {
		limit = len(changes)
	}
	parts := make([]string, 0, limit+1)
	for _, change := range changes[:limit] {
		parts = append(parts, fmt.Sprintf("%s %s", change.Kind, change.Path))
	}
	if len(changes) > limit {
		parts = append(parts, fmt.Sprintf("... and %d more", len(changes)-limit))
	}
	label := "change"
	if len(changes) != 1 {
		label = "changes"
	}
	return fmt.Sprintf("%d %s: %s", len(changes), label, strings.Join(parts, ", "))
}

func scanMtimes(paths ...string) (map[string]time.Time, error) {
	mtimes := map[string]time.Time{}

	for _, p := range paths {
		if p == "" {
			continue
		}
		st, err := os.Stat(p)
		if err != nil {
			if os.IsNotExist(err) {
				continue
			}
			return nil, err
		}
		if !st.IsDir() {
			mtimes[p] = st.ModTime()
			continue
		}
		err = filepath.WalkDir(p, func(path string, d os.DirEntry, err error) error {
			if err != nil {
				return err
			}
			if d.IsDir() {
				return nil
			}
			st, err := d.Info()
			if err != nil {
				return err
			}
			mtimes[path] = st.ModTime()
			return nil
		})
		if err != nil {
			return nil, err
		}
	}
	return mtimes, nil
}

type nativeWatcher interface {
	Events() <-chan struct{}
	Update([]string) error
	Close() error
}

func watchPaths(buildOpts site.BuildOptions) ([]string, error) {
	theme, err := site.EffectiveTheme(buildOpts)
	if err != nil {
		return nil, err
	}

	paths := []string{
		buildOpts.ContentDir,
		buildOpts.StaticDir,
		buildOpts.ConfigPath,
		filepath.Join(buildOpts.ThemesDir, theme),
	}

	seen := make(map[string]struct{}, len(paths))
	uniq := make([]string, 0, len(paths))
	for _, p := range paths {
		if p == "" {
			continue
		}
		clean := filepath.Clean(p)
		if _, ok := seen[clean]; ok {
			continue
		}
		seen[clean] = struct{}{}
		uniq = append(uniq, clean)
	}
	return uniq, nil
}

func rebuildOnWatchChange(buildOpts site.BuildOptions, watcher nativeWatcher, state map[string]time.Time) (map[string]time.Time, bool) {
	paths, err := watchPaths(buildOpts)
	if err != nil {
		log.Printf("watch setup error: %v", err)
		return state, true
	}
	if watcher != nil {
		if err := watcher.Update(paths); err != nil {
			log.Printf("watch update failed, falling back to polling: %v", err)
			return state, false
		}
	}

	next, err := scanMtimes(paths...)
	if err != nil {
		log.Printf("watch scan error: %v", err)
		return state, true
	}

	changes := diffWatchState(state, next)
	if len(changes) == 0 {
		return next, true
	}

	log.Printf("watch rebuild triggered by %s", summarizeWatchChanges(changes, 5))
	if _, err := site.Build(buildOpts); err != nil {
		log.Printf("rebuild failed: %v", err)
	} else {
		log.Printf("rebuild complete")
	}
	return next, true
}

func watchAndRebuildPolling(buildOpts site.BuildOptions, state map[string]time.Time) {
	tick := time.NewTicker(2 * time.Second)
	defer tick.Stop()

	for range tick.C {
		next, ok := rebuildOnWatchChange(buildOpts, nil, state)
		if !ok {
			return
		}
		state = next
	}
}

func waitForWatchBurst(events <-chan struct{}, debounce time.Duration) bool {
	_, ok := <-events
	if !ok {
		return false
	}

	timer := time.NewTimer(debounce)
	defer timer.Stop()

	for {
		select {
		case _, ok := <-events:
			if !ok {
				return false
			}
			if !timer.Stop() {
				select {
				case <-timer.C:
				default:
				}
			}
			timer.Reset(debounce)
		case <-timer.C:
			return true
		}
	}
}
