package server

import (
	"encoding/json"
	"html/template"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"strings"

	"gitlab.com/Timfa/bluegit/internal/access"
	"gitlab.com/Timfa/bluegit/internal/ci"
	"gitlab.com/Timfa/bluegit/internal/gitrepo"
	"gitlab.com/Timfa/bluegit/internal/highlight"
)

const ciFile = "blue-ci-cd.yml"
const ciMaxBytes = 200_000

// CIEditor is de Pipeline Editor voor blue-ci-cd.yml.
type CIEditor struct {
	Ref      string
	Body     string
	Rows     []EditorLine
	Issues   []LintRow
	Errors   int
	Warnings int
	Status   string
	Class    string
}

// EditorLine is één gekleurde regel, met een markering als de linter daar klaagt.
type EditorLine struct {
	N    int
	HTML template.HTML
	Bad  bool
}

// LintRow is één melding onder de editor.
type LintRow struct {
	Line    int    `json:"line"`
	Text    string `json:"text"`
	Warning bool   `json:"warning"`
}

func (s *Server) ciEditor(w http.ResponseWriter, r *http.Request) {
	_, repo, role, ok := s.guard(w, r, access.RoleReadonly)
	if !ok {
		return
	}
	ref := strings.TrimSpace(r.URL.Query().Get("ref"))
	if ref == "" {
		ref = r.URL.Query().Get("rev")
	}
	ref = safeRev(ref, repo.DefaultBranch)
	v := s.repoView(w, r, repo, role, "edit.title")
	v.Wide = true
	v.Page = "editor"
	v.Rev = ref
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	s.branchList(r, &v, dir)
	body := s.ciFileAt(r, dir, ref)
	model := s.ciEditorModel(r, body, s.includeFrom(r, dir, ref))
	model.Ref = ref
	v.Editor = model
	s.render(w, "editor", v)
}

func (s *Server) lintCI(w http.ResponseWriter, r *http.Request) {
	_, repo, _, ok := s.guard(w, r, access.RoleReadonly)
	if !ok || !s.csrfOK(w, r) {
		return
	}
	body := r.FormValue("body")
	if len(body) > ciMaxBytes {
		http.Error(w, s.tr(r, "edit.fail"), http.StatusBadRequest)
		return
	}
	ref := safeRev(r.FormValue("ref"), repo.DefaultBranch)
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	model := s.ciEditorModel(r, body, s.includeFrom(r, dir, ref))
	lines := make([]string, len(model.Rows))
	var bad []int
	for i, row := range model.Rows {
		lines[i] = string(row.HTML)
		if row.Bad {
			bad = append(bad, row.N)
		}
	}
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(map[string]any{
		"status":      model.Status,
		"statusClass": model.Class,
		"errors":      model.Errors,
		"warnings":    model.Warnings,
		"issues":      model.Issues,
		"lines":       lines,
		"bad":         bad,
	})
}

func (s *Server) saveCIEditor(w http.ResponseWriter, r *http.Request) {
	u, repo, role, ok := s.guard(w, r, access.RoleDeveloper)
	if !ok || !s.csrfOK(w, r) {
		return
	}
	base := safeRev(r.FormValue("base"), repo.DefaultBranch)
	branch := strings.TrimSpace(r.FormValue("branch"))
	if !validBranchName(branch) {
		s.redirect(w, r, repoURL(repo)+"/-/ci/editor?ref="+url.QueryEscape(base), "", s.tr(r, "edit.badBranch"))
		return
	}
	back := repoURL(repo) + "/-/ci/editor?ref=" + url.QueryEscape(branch)
	message := strings.TrimSpace(r.FormValue("message"))
	if message == "" {
		s.redirect(w, r, back, "", s.tr(r, "edit.needMessage"))
		return
	}
	body := r.FormValue("body")
	if len(body) > ciMaxBytes {
		s.redirect(w, r, back, "", s.tr(r, "edit.fail"))
		return
	}
	patterns, _ := s.Store.ProtectedPatterns(r.Context(), repo.ID)
	if access.BranchProtected(patterns, branch) && !role.CanPushBranch(true) {
		s.redirect(w, r, back, "", s.tr(r, "edit.protected"))
		return
	}
	dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
	if err := s.ensureBranch(r, dir, branch, base); err != nil {
		s.redirect(w, r, back, "", s.tr(r, "edit.fail"))
		return
	}
	work, err := os.MkdirTemp("", "bluegit-edit-")
	if err != nil {
		s.redirect(w, r, back, "", s.tr(r, "edit.fail"))
		return
	}
	defer os.RemoveAll(work)
	email := u.Username + "@users.git.timfalken.com"
	err = gitrepo.CommitOnBranch(r.Context(), s.Git, dir, work, branch, u.Username, email, message, "", map[string]string{ciFile: body}, role, patterns)
	if err != nil {
		low := strings.ToLower(err.Error())
		if strings.Contains(low, "nothing to commit") || strings.Contains(low, "nothing added") {
			s.redirect(w, r, back, "", s.tr(r, "edit.same"))
			return
		}
		if s.Log != nil {
			s.Log.Error("ci-editor", "err", err)
		}
		s.redirect(w, r, back, "", s.tr(r, "edit.fail"))
		return
	}
	s.redirect(w, r, back, s.tr(r, "edit.saved"), "")
}

func (s *Server) ciEditorModel(r *http.Request, body string, read func(string) ([]byte, error)) *CIEditor {
	_, issues := ci.Lint([]byte(body), read)
	bad := map[int]bool{}
	var rows []LintRow
	errors, warnings := 0, 0
	for _, is := range issues {
		line := is.Line
		if line < 1 {
			line = 1
		}
		text := s.tr(r, is.Key, is.Args...)
		rows = append(rows, LintRow{Line: line, Text: text, Warning: is.Warning})
		if is.Warning {
			warnings++
			continue
		}
		errors++
		bad[line] = true
	}
	painted := highlight.Lines(ciFile, body)
	if len(painted) == 0 {
		painted = []string{""}
	}
	if strings.HasSuffix(body, "\n") {
		painted = append(painted, "")
	}
	lines := make([]EditorLine, len(painted))
	for i, htmlLine := range painted {
		n := i + 1
		lines[i] = EditorLine{N: n, HTML: template.HTML(htmlLine), Bad: bad[n]}
	}
	status, class := s.tr(r, "edit.clean"), "passed"
	if errors > 0 {
		key := "edit.issues"
		if errors == 1 {
			key = "edit.issueOne"
		}
		status, class = s.tr(r, key, errors), "failed"
	} else if warnings > 0 {
		key := "edit.warnings"
		if warnings == 1 {
			key = "edit.warningOne"
		}
		status, class = s.tr(r, key, warnings), "warning"
	}
	if rows == nil {
		rows = []LintRow{}
	}
	return &CIEditor{
		Body: body, Rows: lines, Issues: rows,
		Errors: errors, Warnings: warnings, Status: status, Class: class,
	}
}

func (s *Server) ciFileAt(r *http.Request, dir, ref string) string {
	out, err := exec.CommandContext(r.Context(), s.Git, "-C", dir, "show", ref+":"+ciFile).Output()
	if err != nil || len(out) > ciMaxBytes {
		return ""
	}
	return string(out)
}

func (s *Server) includeFrom(r *http.Request, dir, ref string) func(string) ([]byte, error) {
	return func(path string) ([]byte, error) {
		if !validInclude(path) {
			return nil, os.ErrInvalid
		}
		return exec.CommandContext(r.Context(), s.Git, "-C", dir, "show", ref+":"+path).Output()
	}
}

func (s *Server) ensureBranch(r *http.Request, dir, branch, base string) error {
	if gitOne(r.Context(), s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch) != "" {
		return nil
	}
	if gitOne(r.Context(), s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+base) == "" {
		return os.ErrNotExist
	}
	cmd := exec.CommandContext(r.Context(), s.Git, "-C", dir, "branch", branch, base)
	if out, err := cmd.CombinedOutput(); err != nil {
		if s.Log != nil {
			s.Log.Error("ci-branch", "err", err, "out", string(out))
		}
		return err
	}
	return nil
}

func validBranchName(s string) bool {
	if s == "" || s == "@" || strings.HasPrefix(s, "-") || strings.HasPrefix(s, "/") || strings.HasSuffix(s, "/") || strings.HasSuffix(s, ".") || strings.Contains(s, "..") || strings.Contains(s, "//") || strings.Contains(s, "@{") {
		return false
	}
	return !strings.ContainsAny(s, " \t\n~^:?*[\\")
}

func validInclude(p string) bool {
	if p == "" || strings.HasPrefix(p, "/") || strings.Contains(p, `\`) || strings.Contains(p, "..") {
		return false
	}
	return true
}
