package server

import (
	"context"
	"fmt"
	"html/template"
	"net/http"
	"path"
	"sort"
	"strings"

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

func (s *Server) fillOverview(r *http.Request, v *View, repo store.Repo) {
	v.Page = "overview"
	s.branchList(r, v, repo)
	s.fillGraph(r, v, repo)
	lang := i18n.Parse(v.Lang)
	if c, err := s.cLastCommit(r.Context(), repo, v.Rev, ""); err == nil && c.SHA != "" {
		if rows := s.presentCommits(r.Context(), repo.ID, []gitrepo.Commit{c}, lang); len(rows) > 0 {
			s.attachHeadPipeline(r.Context(), repo, &rows[0], lang)
			v.Head = &rows[0]
		}
	}
	entries, err := s.cTree(r.Context(), repo, v.Rev, "")
	touch, _ := s.cTouch(r.Context(), repo, v.Rev)
	if err == nil {
		v.Files = fileRows(entries, "", touch, lang)
	}
	readme, license := findDocs(entries)
	v.LicensePath = license
	if readme != "" {
		text, binary, err := s.cDoc(r.Context(), repo, v.Rev, readme, 200_000)
		if err == nil && !binary {
			v.ReadmeName = readme
			v.Readme = s.renderDoc(r, repo, v.Rev, "", text)
		}
	}
	commits, branches, tags, _ := s.cStats(r.Context(), repo, v.Rev)
	v.NCommits, v.NBranches, v.NTags = commits, branches, tags
	if rels, err := s.Store.ListReleases(r.Context(), repo.ID); err == nil && v.ShowReleases {
		v.NReleases = len(rels)
	}
	v.Created = i18n.FormatDate(lang, repo.CreatedAt)
}

func (s *Server) fillFiles(r *http.Request, v *View, repo store.Repo, rel string, isFile bool) {
	v.Page = "files"
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	lang := i18n.Parse(v.Lang)
	s.branchList(r, v, repo)
	all, _ := s.cTreeAll(r.Context(), repo, v.Rev)
	v.Tree = treeRows(all, rel)
	if !isFile {
		v.TreePath = rel
		entries, err := s.cTree(r.Context(), repo, v.Rev, rel)
		touch, _ := s.cTouch(r.Context(), repo, v.Rev)
		if err == nil {
			v.Files = fileRows(entries, rel, touch, lang)
			// Een README in een submap staat onder de bestandslijst, met
			// links en afbeeldingen relatief aan die map.
			if readme, _ := findDocs(entries); readme != "" {
				if text, binary, err := s.cDoc(r.Context(), repo, v.Rev, path.Join(rel, readme), 200_000); err == nil && !binary {
					v.ReadmeName = readme
					v.Readme = s.renderDoc(r, repo, v.Rev, rel, text)
				}
			}
		}
		return
	}
	v.BlobPath = rel
	v.FileName = path.Base(rel)
	text, binary, err := gitrepo.Blob(r.Context(), s.Git, dir, v.Rev, rel, 200_000)
	if err != nil {
		return
	}
	v.Binary = binary
	v.IsSVG = strings.EqualFold(path.Ext(rel), ".svg")
	if !binary && isMarkdownName(v.FileName) {
		v.MDView = true
		v.Readme = s.renderDoc(r, repo, v.Rev, path.Dir(rel), text)
	}
	if !binary {
		for i, line := range highlight.Lines(rel, text) {
			v.Lines = append(v.Lines, CodeLine{N: i + 1, HTML: template.HTML(line)})
		}
	}
	if n, err := gitrepo.BlobSize(r.Context(), s.Git, dir, v.Rev, rel); err == nil {
		v.BlobSize = formatSize(n)
		if binary && n <= rawMax && rawImageTypes[strings.ToLower(path.Ext(rel))] != "" {
			if data, err := gitrepo.BlobText(r.Context(), s.Git, dir, v.Rev, rel); err == nil {
				v.IsImage = rasterImageType(rel, data) != ""
			}
		}
	}
	if c, err := s.cLastCommit(r.Context(), repo, v.Rev, rel); err == nil && c.SHA != "" {
		if rows := s.presentCommits(r.Context(), repo.ID, []gitrepo.Commit{c}, lang); len(rows) > 0 {
			s.attachHeadPipeline(r.Context(), repo, &rows[0], lang)
			v.Head = &rows[0]
		}
	}
}

func (s *Server) branchList(r *http.Request, v *View, repo store.Repo) {
	patterns, _ := s.Store.ProtectedPatterns(r.Context(), v.Repo.ID)
	v.RevProtected = access.BranchProtected(patterns, v.Rev)
	names, _ := s.cBranches(r.Context(), repo)
	seen := false
	for _, name := range names {
		if name == v.Rev {
			seen = true
		}
		v.Branches = append(v.Branches, BranchRow{Name: name, Protected: access.BranchProtected(patterns, name)})
	}
	if v.Rev != "" && !seen {
		v.Branches = append([]BranchRow{{Name: v.Rev, Protected: v.RevProtected}}, v.Branches...)
	}
}

func (s *Server) attachHeadPipeline(ctx context.Context, repo store.Repo, row *CommitRow, lang i18n.Lang) {
	if row == nil || row.SHA == "" || s.Store == nil {
		return
	}
	p, err := s.Store.LatestPipelineByCommit(ctx, repo.ID, row.SHA)
	if err != nil {
		return
	}
	jobs, _ := s.Store.JobsByPipeline(ctx, p.ID)
	status := displayStatus(s.pipeStatusFor(p), jobs)
	row.PipeID = p.ID
	row.PipeStatus = status
	row.PipeLabel = i18n.T(lang, "pipe."+status)
	row.PipeDuration = pipelineClock(p)
	tr := func(key string, args ...any) string { return i18n.T(lang, key, args...) }
	row.PipeStages = stageViews(jobs, s.queueRanks(ctx), tr)
	row.PipeLive = jobsLive(p.Status, jobs)
	row.PipeFailed = jobsFailed(jobs)
}

func fileRows(entries []gitrepo.Entry, base string, touch map[string]gitrepo.Commit, lang i18n.Lang) []FileRow {
	var out []FileRow
	for _, e := range entries {
		p := e.Name
		if base != "" {
			p = base + "/" + e.Name
		}
		row := FileRow{Name: e.Name, Path: p, Dir: e.Type == "tree", Icon: fileIcon(e.Name, e.Type)}
		if c, ok := touch[p]; ok {
			row.Subject = c.Subject
			row.When = i18n.Ago(lang, c.Unix)
			row.SHA = c.SHA
		}
		out = append(out, row)
	}
	sort.Slice(out, func(i, j int) bool {
		if out[i].Dir != out[j].Dir {
			return out[i].Dir
		}
		return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name)
	})
	return out
}

func treeRows(entries []gitrepo.Entry, current string) []FileRow {
	var out []FileRow
	for _, e := range entries {
		base := e.Name
		if i := strings.LastIndex(e.Name, "/"); i >= 0 {
			base = e.Name[i+1:]
		}
		depth := strings.Count(e.Name, "/")
		if depth > 8 {
			depth = 8
		}
		dir := e.Type == "tree"
		inside := current == e.Name || strings.HasPrefix(current, e.Name+"/")
		active := e.Name == current
		if dir && inside {
			active = true
		}
		out = append(out, FileRow{
			Name: base, Path: e.Name, Dir: dir, Icon: fileIcon(base, e.Type),
			Depth: depth, Active: active, Open: dir && inside,
		})
	}
	return out
}

func findDocs(entries []gitrepo.Entry) (readme, license string) {
	readmeRank := 9
	for _, e := range entries {
		if e.Type != "blob" {
			continue
		}
		low := strings.ToLower(e.Name)
		rank := 9
		switch low {
		case "readme.md":
			rank = 0
		case "readme.markdown":
			rank = 1
		case "readme":
			rank = 2
		}
		if rank < readmeRank {
			readmeRank = rank
			readme = e.Name
		}
		switch low {
		case "license", "license.md", "license.txt", "licence", "copying":
			if license == "" || low == "license" {
				license = e.Name
			}
		}
	}
	return readme, license
}

func fileIcon(name, typ string) string {
	if typ == "tree" {
		return "dir"
	}
	switch strings.ToLower(path.Ext(name)) {
	case ".md", ".markdown":
		return "md"
	case ".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp":
		return "img"
	case ".go", ".js", ".ts", ".py", ".rs", ".c", ".h", ".rb", ".sh":
		return "code"
	case ".yml", ".yaml", ".toml", ".json", ".lock":
		return "cfg"
	}
	base := strings.ToLower(name)
	if base == "license" || base == "licence" || base == "copying" || strings.HasPrefix(base, "license.") {
		return "lic"
	}
	if strings.HasPrefix(base, "readme") {
		return "md"
	}
	return "file"
}

func formatSize(n int64) string {
	if n < 1024 {
		return fmt.Sprintf("%d B", n)
	}
	if n < 1024*1024 {
		return fmt.Sprintf("%.1f KiB", float64(n)/1024)
	}
	return fmt.Sprintf("%.1f MiB", float64(n)/(1024*1024))
}

// renderDoc rendert een Markdown-document uit map dir (leeg of "." is de
// root). Relatieve links gaan naar /-/blob/, afbeeldingen naar /-/raw/,
// beide op dezelfde ref.
func (s *Server) renderDoc(r *http.Request, repo store.Repo, rev, dir, text string) template.HTML {
	base := "/" + repo.FullPath() + "/-/blob/"
	if dir = strings.Trim(dir, "/"); dir != "" && dir != "." {
		base += dir + "/"
	}
	return template.HTML(markdown.RenderTasks(text, base, rev, "/"+repo.FullPath(), markdown.Tasks{Count: s.tr(r, "tpl.tasks")}))
}

func isMarkdownName(name string) bool {
	switch strings.ToLower(path.Ext(name)) {
	case ".md", ".markdown":
		return true
	}
	return strings.EqualFold(name, "readme")
}
