package server

import (
	"context"
	"strconv"
	"time"

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

func (s *Server) heatmap(ctx context.Context, userID int64, repoIDs []int64, lang i18n.Lang) *activity.Calendar {
	s.syncRepos(ctx, repoIDs)
	loc := activity.Location()
	since := time.Now().In(loc).AddDate(-1, 0, -3)
	times, err := s.Store.ContributionTimes(ctx, userID, repoIDs, since)
	counts := map[string]int{}
	if err == nil {
		for _, ts := range times {
			counts[ts.In(loc).Format("2006-01-02")]++
		}
	}
	cal := activity.Build(time.Now(), counts, lang)
	return &cal
}

func (s *Server) visibleIDs(ctx context.Context, userID int64, repos []store.Repo) []int64 {
	allowed, err := s.Store.ListRepoIDs(ctx, userID)
	if err != nil {
		return nil
	}
	set := map[int64]bool{}
	for _, id := range allowed {
		set[id] = true
	}
	var ids []int64
	for _, repo := range repos {
		if set[repo.ID] {
			ids = append(ids, repo.ID)
		}
	}
	return ids
}

func (s *Server) syncRepos(ctx context.Context, repoIDs []int64) {
	if s.StoragePath() == "" {
		return
	}
	for _, id := range repoIDs {
		done, err := s.Store.ContributionSynced(ctx, id)
		if err != nil || done {
			continue
		}
		repo, err := s.Store.RepoByID(ctx, id)
		if err != nil {
			continue
		}
		if err := s.backfillRepo(ctx, repo); err != nil {
			if s.Log != nil {
				s.Log.Error("bijdragen", "err", err)
			}
			continue
		}
		_ = s.Store.MarkContributionSynced(ctx, id)
	}
}

func (s *Server) backfillRepo(ctx context.Context, repo store.Repo) error {
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	refs, err := gitrepo.Refs(ctx, s.Git, dir)
	if err != nil {
		return err
	}
	pushers, err := s.Store.PushersByRepo(ctx, repo.ID)
	if err != nil {
		return err
	}
	var rows []store.Contribution
	seen := map[string]bool{}
	for ref, sha := range refs {
		if _, ok := gitrepo.BranchOfRef(ref); !ok {
			continue
		}
		list, err := gitrepo.CommitsSince(ctx, s.Git, dir, "", sha)
		if err != nil {
			return err
		}
		for _, c := range list {
			if seen[c.SHA] {
				continue
			}
			seen[c.SHA] = true
			uid, ok := s.Store.UserIDByGitAuthor(ctx, c.Email)
			if !ok {
				if p, found := pushers[c.SHA]; found && p.UserID != 0 {
					uid = p.UserID
					ok = true
				}
			}
			if !ok {
				continue
			}
			when := time.Unix(c.Unix, 0).UTC()
			if c.Unix <= 0 {
				when = time.Now().UTC()
			}
			rows = append(rows, store.Contribution{
				UserID: uid, RepoID: repo.ID, Kind: "commit", Ref: c.SHA, At: when,
			})
		}
	}
	return s.Store.AddContributions(ctx, rows)
}

func (s *Server) recordPushContributions(repo store.Repo, user store.User, before, after map[string]string) {
	if s.Store == nil || user.ID == 0 || s.StoragePath() == "" || after == nil {
		return
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	ctx := context.Background()
	var rows []store.Contribution
	var authors []store.PushAuthor
	for ref, sha := range after {
		if before[ref] == sha {
			continue
		}
		if _, ok := gitrepo.BranchOfRef(ref); !ok {
			continue
		}
		list, err := gitrepo.CommitsSince(ctx, s.Git, dir, before[ref], sha)
		if err != nil {
			if s.Log != nil {
				s.Log.Error("bijdragen", "err", err)
			}
			continue
		}
		for _, c := range list {
			authors = append(authors, store.PushAuthor{SHA: c.SHA, Name: c.Name, Email: c.Email})
			uid := user.ID
			if id, ok := s.Store.UserIDByGitAuthor(ctx, c.Email); ok {
				uid = id
			}
			when := time.Unix(c.Unix, 0).UTC()
			if c.Unix <= 0 {
				when = time.Now().UTC()
			}
			rows = append(rows, store.Contribution{
				UserID: uid, RepoID: repo.ID, Kind: "commit", Ref: c.SHA, At: when,
			})
		}
	}
	if err := s.Store.RememberPushers(ctx, repo.ID, user.ID, authors); err != nil && s.Log != nil {
		s.Log.Error("pusher", "err", err)
	}
	if err := s.Store.AddContributions(ctx, rows); err != nil && s.Log != nil {
		s.Log.Error("bijdragen", "err", err)
	}
}

func (s *Server) recordContribution(userID, repoID int64, kind, ref string, at time.Time) {
	if s.Store == nil || userID == 0 || repoID == 0 || ref == "" {
		return
	}
	if at.IsZero() {
		at = time.Now().UTC()
	}
	if err := s.Store.AddContributions(context.Background(), []store.Contribution{{
		UserID: userID, RepoID: repoID, Kind: kind, Ref: ref, At: at,
	}}); err != nil && s.Log != nil {
		s.Log.Error("bijdragen", "err", err)
	}
}

func mrRef(id int64) string { return "mr:" + strconv.FormatInt(id, 10) }
