package server

import (
	"context"
	"net/http"
	"strings"
	"sync"
	"time"

	"gitlab.com/Timfa/bluegit/internal/gitrepo"
	"gitlab.com/Timfa/bluegit/internal/i18n"
	"gitlab.com/Timfa/bluegit/internal/store"
)

// gitMaintFirstDelay is de pauze na het starten, zodat de website
// eerst opkomt. In tests lager zetten.
var gitMaintFirstDelay = 2 * time.Minute

// gitMaintRepoTimeout is de maximale duur per repository.
var gitMaintRepoTimeout = gitrepo.DefaultMaintTimeout

// GitMaintRepoResult is de uitkomst voor één repository.
type GitMaintRepoResult struct {
	Repo     string `json:"repo"`
	OK       bool   `json:"ok"`
	Duration int64  `json:"duration_ms"`
	Error    string `json:"error,omitempty"`
}

// GitMaintReport is de laatste onderhoudsronde.
type GitMaintReport struct {
	Started  time.Time            `json:"started,omitempty"`
	Finished time.Time            `json:"finished,omitempty"`
	Repos    int                  `json:"repos"`
	OK       int                  `json:"ok"`
	Skipped  int                  `json:"skipped"`
	Error    string               `json:"error,omitempty"`
	Results  []GitMaintRepoResult `json:"results,omitempty"`
}

type gitMaintState struct {
	mu      sync.Mutex
	running bool
	last    GitMaintReport
}

// GitMaintenanceSweeper draait periodiek onderhoud op alle bare
// repositories. Uit als maintenance_interval "off" is.
func (s *Server) GitMaintenanceSweeper(ctx context.Context) {
	every, on, err := s.Cfg.Git.MaintenanceEvery()
	if err != nil {
		if s.Log != nil {
			s.Log.Error("git maintenance", "err", err)
		}
		return
	}
	if !on {
		if s.Log != nil {
			s.Log.Info("git maintenance disabled")
		}
		return
	}
	if s.Log != nil {
		s.Log.Info("git maintenance scheduled", "interval", every.String())
	}
	first := time.NewTimer(gitMaintFirstDelay)
	defer first.Stop()
	tick := time.NewTicker(every)
	defer tick.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-first.C:
		case <-tick.C:
		}
		s.RunGitMaintenance(ctx, "")
	}
}

// RunGitMaintenance onderhoudt alle bare repositories, of één als
// repoPath (eigenaar/naam) gezet is. Eén ronde tegelijk; een tweede
// aanroep krijgt ok=false. Fouten op één repo slaan die over.
func (s *Server) RunGitMaintenance(ctx context.Context, repoPath string) (GitMaintReport, bool) {
	s.gitMaint.mu.Lock()
	if s.gitMaint.running {
		s.gitMaint.mu.Unlock()
		return s.gitMaint.last, false
	}
	s.gitMaint.running = true
	s.gitMaint.mu.Unlock()
	defer func() {
		s.gitMaint.mu.Lock()
		s.gitMaint.running = false
		s.gitMaint.mu.Unlock()
	}()

	rep := GitMaintReport{Started: time.Now().UTC()}
	defer func() {
		rep.Finished = time.Now().UTC()
		s.gitMaint.mu.Lock()
		s.gitMaint.last = rep
		s.gitMaint.mu.Unlock()
	}()

	storage := s.StoragePath()
	if storage == "" {
		if s.Log != nil {
			s.Log.Info("git maintenance skipped", "reason", "no storage")
		}
		return rep, true
	}
	repos, err := s.reposForMaintenance(ctx, repoPath)
	if err != nil {
		rep.Error = err.Error()
		if s.Log != nil {
			s.Log.Error("git maintenance list", "err", err)
		}
		return rep, true
	}
	gitBin := s.Git
	if gitBin == "" {
		gitBin = s.Cfg.Git.Binary
	}
	for _, repo := range repos {
		if ctx.Err() != nil {
			break
		}
		path := gitrepo.Dir(storage, repo.OwnerPath, repo.Name)
		name := repo.FullPath()
		repoCtx, cancel := context.WithTimeout(ctx, gitMaintRepoTimeout)
		res := gitrepo.Maintain(repoCtx, gitBin, path)
		cancel()
		item := GitMaintRepoResult{Repo: name, OK: res.OK, Duration: res.Duration.Milliseconds(), Error: res.Err}
		rep.Repos++
		if res.OK {
			rep.OK++
			if s.Log != nil {
				s.Log.Info("git maintenance", "repo", name, "duration", res.Duration.Round(time.Millisecond).String())
			}
		} else {
			rep.Skipped++
			if s.Log != nil {
				s.Log.Error("git maintenance skip", "repo", name, "err", res.Err)
			}
		}
		rep.Results = append(rep.Results, item)
	}
	if s.Log != nil {
		s.Log.Info("git maintenance done", "repos", rep.Repos, "ok", rep.OK, "skipped", rep.Skipped)
	}
	return rep, true
}

func (s *Server) reposForMaintenance(ctx context.Context, repoPath string) ([]store.Repo, error) {
	if repoPath == "" {
		return s.Store.AllRepos(ctx)
	}
	owner, name, ok := splitRepoPath(repoPath)
	if !ok {
		return nil, errBadRepoPath
	}
	repo, err := s.Store.RepoByPath(ctx, owner, name)
	if err != nil {
		return nil, err
	}
	return []store.Repo{repo}, nil
}

func splitRepoPath(p string) (owner, name string, ok bool) {
	p = strings.Trim(strings.TrimSpace(p), "/")
	owner, name, ok = strings.Cut(p, "/")
	if !ok || owner == "" || name == "" || strings.Contains(name, "/") {
		return "", "", false
	}
	return owner, name, true
}

var errBadRepoPath = fail(400, i18n.E("err.notFound"))

func (s *Server) gitMaintStatus() map[string]any {
	every, on, err := s.Cfg.Git.MaintenanceEvery()
	interval := ""
	if err == nil && on {
		interval = every.String()
	}
	s.gitMaint.mu.Lock()
	defer s.gitMaint.mu.Unlock()
	out := map[string]any{
		"enabled":  on && err == nil,
		"interval": interval,
		"running":  s.gitMaint.running,
	}
	last := s.gitMaint.last
	if !last.Started.IsZero() {
		out["last_started"] = last.Started.Format(time.RFC3339)
		out["last_finished"] = last.Finished.Format(time.RFC3339)
		out["repos"] = last.Repos
		out["ok"] = last.OK
		out["skipped"] = last.Skipped
		out["results"] = last.Results
		if last.Error != "" {
			out["error"] = last.Error
		}
	}
	return out
}

func (s *Server) apiAdminGitMaintenance(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.MethodPost {
		var in struct {
			Repo string `json:"repo"`
		}
		if err := readJSON(r, &in); err != nil {
			s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
			return
		}
		rep, started := s.RunGitMaintenance(r.Context(), in.Repo)
		if !started {
			http.Error(w, "maintenance already running\n", http.StatusConflict)
			return
		}
		writeJSON(w, http.StatusOK, s.reportJSON(rep))
		return
	}
	writeJSON(w, http.StatusOK, s.gitMaintStatus())
}

func (s *Server) reportJSON(rep GitMaintReport) map[string]any {
	out := s.gitMaintStatus()
	out["repos"] = rep.Repos
	out["ok"] = rep.OK
	out["skipped"] = rep.Skipped
	out["results"] = rep.Results
	if rep.Error != "" {
		out["error"] = rep.Error
	}
	if !rep.Started.IsZero() {
		out["last_started"] = rep.Started.Format(time.RFC3339)
	}
	if !rep.Finished.IsZero() {
		out["last_finished"] = rep.Finished.Format(time.RFC3339)
	}
	return out
}
