package server

import (
	"encoding/json"
	"errors"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"gitlab.com/Timfa/bluegit/internal/i18n"
	"gitlab.com/Timfa/bluegit/internal/readcache"
	"gitlab.com/Timfa/bluegit/internal/state"
)

// cacheFile staat in de state-map en wint van config.yml, net als storage_path.
const cacheFile = "cache.json"

// CacheSetting is het gekozen cachepad. Leeg = geen cache.
type CacheSetting struct {
	Path  string `json:"path"`
	MaxMB int64  `json:"max_mb"`
}

func (s *Server) savedCache() (CacheSetting, bool) {
	if s.StateDir == "" {
		return CacheSetting{}, false
	}
	b, err := os.ReadFile(filepath.Join(s.StateDir, cacheFile))
	if err != nil {
		return CacheSetting{}, false
	}
	var c CacheSetting
	if json.Unmarshal(b, &c) != nil {
		return CacheSetting{}, false
	}
	return c, true
}

// CacheConfig is wat nu geldt: opgeslagen keuze, anders config/env.
func (s *Server) CacheConfig() CacheSetting {
	if c, ok := s.savedCache(); ok {
		return c
	}
	return CacheSetting{Path: strings.TrimSpace(s.Cfg.CachePath), MaxMB: s.Cfg.CacheMaxMB}
}

// InitReadCache opent de cache bij het starten. Een fout zet de cache uit.
func (s *Server) InitReadCache() {
	c := s.CacheConfig()
	if err := s.openCache(c); err != nil && s.Log != nil {
		s.Log.Warn("leescache uit", "path", c.Path, "err", err)
	}
}

func (s *Server) openCache(c CacheSetting) error {
	if strings.TrimSpace(c.Path) == "" {
		s.SetReadCache(nil)
		return nil
	}
	if !filepath.IsAbs(c.Path) {
		return i18n.E("err.cacheAbs")
	}
	rc, err := readcache.Open(c.Path, c.MaxMB<<20)
	if err != nil {
		s.SetReadCache(nil)
		return err
	}
	s.SetReadCache(rc)
	return nil
}

func (s *Server) opSetCache(path string, maxMB int64) error {
	path = strings.TrimSpace(path)
	if path != "" {
		path = filepath.Clean(path)
		if !filepath.IsAbs(path) {
			return fail(400, i18n.E("err.cacheAbs"))
		}
		for _, other := range []string{s.StoragePath(), s.StateDir} {
			if other != "" && (path == filepath.Clean(other) || strings.HasPrefix(path+"/", filepath.Clean(other)+"/")) {
				return fail(400, i18n.E("err.cacheInside"))
			}
		}
		if err := os.MkdirAll(filepath.Join(path, "cache"), 0o750); err != nil {
			return fail(400, i18n.E("err.cacheDir", err.Error()))
		}
		probe, err := os.CreateTemp(filepath.Join(path, "cache"), ".tmp-probe-*")
		if err != nil {
			return fail(400, i18n.E("err.cacheDir", err.Error()))
		}
		probe.Close()
		_ = os.Remove(probe.Name())
	}
	if maxMB < 0 {
		maxMB = 0
	}
	c := CacheSetting{Path: path, MaxMB: maxMB}
	if s.StateDir == "" {
		return fail(400, errors.New("geen state-map"))
	}
	b, _ := json.Marshal(c)
	tmp := filepath.Join(s.StateDir, cacheFile+".tmp")
	if err := os.WriteFile(tmp, b, 0o640); err != nil {
		return fail(500, err)
	}
	if err := os.Rename(tmp, filepath.Join(s.StateDir, cacheFile)); err != nil {
		return fail(500, err)
	}
	if err := s.openCache(c); err != nil {
		return fail(400, err)
	}
	return nil
}

// cacheInfo is de stand voor Beheer en de API.
func (s *Server) cacheInfo() map[string]any {
	c := s.CacheConfig()
	u := s.ReadCache().Usage()
	out := map[string]any{
		"path": c.Path, "max_mb": c.MaxMB, "enabled": s.ReadCache() != nil,
		"bytes": u.Bytes, "max_bytes": u.Max, "entries": u.Entries, "hits": u.Hits, "misses": u.Misses,
		"locations": s.locations(),
		"bytes_h":   state.Format(uint64(u.Bytes)), "max_h": state.Format(uint64(u.Max)),
	}
	return out
}

// locations zegt waar wat staat, met het soort schijf.
func (s *Server) locations() []map[string]string {
	var out []map[string]string
	add := func(what, p string) {
		if p != "" {
			out = append(out, map[string]string{"what": what, "path": p, "disk": state.DiskKind(p)})
		}
	}
	add("database", filepath.Join(s.StateDir, "bluegit.db"))
	add("logos", filepath.Join(s.StateDir, "logos"))
	if st := s.StoragePath(); st != "" {
		add("repos", filepath.Join(st, "repos"))
		add("artifacts", filepath.Join(st, "artifacts"))
	}
	if c := s.ReadCache(); c != nil {
		add("cache", c.Dir())
	}
	return out
}

func (s *Server) apiAdminCache(w http.ResponseWriter, r *http.Request) {
	if !apiUser(r).InstanceAdmin {
		s.writeAPIErr(w, r, fail(403, i18n.E("err.forbidden")))
		return
	}
	if r.Method == http.MethodPut {
		var in CacheSetting
		if err := readJSON(r, &in); err != nil {
			s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
			return
		}
		if !s.apiOK(w, r, s.opSetCache(in.Path, in.MaxMB)) {
			return
		}
	}
	writeJSON(w, http.StatusOK, s.cacheInfo())
}

func (s *Server) apiAdminCacheClear(w http.ResponseWriter, r *http.Request) {
	if !apiUser(r).InstanceAdmin {
		s.writeAPIErr(w, r, fail(403, i18n.E("err.forbidden")))
		return
	}
	s.ReadCache().Clear()
	writeJSON(w, http.StatusOK, s.cacheInfo())
}

func (s *Server) setupCacheSave(w http.ResponseWriter, r *http.Request) {
	if _, ok := s.adminOnly(w, r); !ok || !s.csrfOK(w, r) {
		return
	}
	maxMB, _ := strconv.ParseInt(strings.TrimSpace(r.FormValue("max_mb")), 10, 64)
	if err := s.opSetCache(r.FormValue("cache_path"), maxMB); err != nil {
		s.renderSetup(w, r, s.trErr(r, err), "")
		return
	}
	s.redirect(w, r, "/setup", s.tr(r, "setup.cacheSaved"), "")
}

func (s *Server) setupCacheClear(w http.ResponseWriter, r *http.Request) {
	if _, ok := s.adminOnly(w, r); !ok || !s.csrfOK(w, r) {
		return
	}
	s.ReadCache().Clear()
	s.redirect(w, r, "/setup", s.tr(r, "setup.cacheCleared"), "")
}
