// Copyright 2024 WIT.COM Inc Licensed GPL 3.0

package main

import (
	"os"
	"path/filepath"

	"go.wit.com/lib/gui/shell"
	"go.wit.com/lib/protobuf/forgepb"
	"go.wit.com/lib/protobuf/gitpb"
	"go.wit.com/log"
)

// returns bad if patches can not be applied
func dumpPatchset(pset *forgepb.Patchset) bool {
	log.Info("applyPatches() NAME", pset.Name)
	log.Info("applyPatches() COMMENT", pset.Comment)
	log.Info("applyPatches() GIT_AUTHOR_NAME", pset.GetGitAuthorName())
	log.Info("applyPatches() GIT_AUTHOR_EMAIL", pset.GetGitAuthorEmail())
	log.Info("applyPatches() Branch Name", pset.GetStartBranchName())
	log.Info("applyPatches() Start Hash", pset.GetStartBranchHash())

	var count int
	var bad int
	all := pset.Patches.SortByFilename()
	for all.Scan() {
		p := all.Next()
		if IsValidPatch(p) {
			// ok
		} else {
			bad += 1
		}
		count += 1
	}
	log.Info("pset has", count, "total patches, ", bad, "bad patches")
	if bad == 0 {
		return true
	}
	return false
}

func IsValidPatch(p *forgepb.Patch) bool {
	basepath, filename := filepath.Split(p.Filename)
	repo := me.forge.FindByGoPath(basepath)
	if repo == nil {
		log.Info("can not apply patch! repo not found", basepath, filename)
		return false
	}
	if repo.DevelHash() != p.StartHash {
		log.Info("can not apply patch! devel hash mismatch", basepath, filename)
		return false
	}
	log.Info("start:", p.StartHash, "end:", p.CommitHash, "file:", basepath, filename, "devel version", repo.GetDevelVersion())
	for _, line := range p.Files {
		log.Info("\t", line)
	}
	return true
}

// re-run git CheckDirty() on everything
func IsAnythingDirty() bool {
	me.found = new(gitpb.Repos)
	findAll() // select all the repos
	doCheckDirtyAndConfigSave()
	me.found = new(gitpb.Repos)
	findDirty()
	if len(me.found.Repos) == 0 {
		return false
	} else {
		return true
	}
}

// From 18ee541f89be2e9f9a91c54873da87885e8ffdf5 Mon Sep 17 00:00:00 2001
// From: Jeff Carr <jcarr@wit.com>
// Date: Sun, 5 Jan 2025 01:18:47 -0600
// Subject: [PATCH] 'forge dirty' will find and list only dirty repos

// list patches in jcarr but not in devel
// git log --format="%H %Subject" jcarr --not devel
func countCurrentPatches(repo *gitpb.Repo) int {
	cmd := []string{"git", "log", "--format=\"%H %s\"", "--no-merges", "jcarr", "--not", "devel"}
	result := repo.Run(cmd)
	return len(result.Stdout)
}

func applyPatchset(pset *forgepb.Patchset) error {
	var everythingworked bool = true
	tmpdir, err := os.MkdirTemp("", "forge")
	if err != nil {
		return err
	}
	// log.Info("got to applyPatches() pset", pset)
	log.Info("applyPatches() NAME", pset.Name)
	log.Info("applyPatches() COMMENT", pset.Comment)
	log.Info("applyPatches() GIT_AUTHOR_NAME", pset.GetGitAuthorName())
	log.Info("applyPatches() GIT_AUTHOR_EMAIL", pset.GetGitAuthorEmail())
	all := pset.Patches.SortByFilename()
	for all.Scan() {
		p := all.Next()
		// log.Info("pset filename FILENAME IS REAL?", p.Filename, pset.Name, pset.Comment)
		basepath, filename := filepath.Split(p.Filename)
		fullpath := filepath.Join(me.forge.GetGoSrc(), basepath)
		log.Info("pset filename FILENAME IS REAL? fullpath", fullpath)
		fullTmpdir := filepath.Join(tmpdir, basepath)
		err := os.MkdirAll(fullTmpdir, os.ModePerm)
		if err != nil {
			log.Info("applyPathces() MkdirAll failed for", fullTmpdir)
			log.Info("applyPathces() MkdirAll failed err", err)
			everythingworked = false
			continue
		}
		log.Info("pset filename FILENAME IS REAL? tmp fullTmpdir", fullTmpdir)
		tmpname := filepath.Join(fullTmpdir, filename)
		raw, _ := os.OpenFile(tmpname, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
		raw.Write(p.Data)
		raw.Close()
		cmd := []string{"git", "am", tmpname}
		result := shell.PathRun(fullpath, cmd)
		if result.Exit != 0 {
			log.Info("cmd failed", cmd, result.Exit)
			everythingworked = false
		}
		// until 'git am' works
		everythingworked = false
	}
	if everythingworked {
		os.RemoveAll(tmpdir) // clean up
	}
	log.Info("THIS IS THE END MY FRIEND")
	return nil
}

func readPatchFile(pbfile string) (*forgepb.Patchset, error) {
	bytes, err := os.ReadFile(pbfile)
	if err != nil {
		log.Info("readfile error", pbfile, err)
		return nil, err
	}
	return handleBytes(bytes)
}

func handleBytes(bytes []byte) (*forgepb.Patchset, error) {
	var pset *forgepb.Patchset
	pset = new(forgepb.Patchset)
	err := pset.Unmarshal(bytes)
	if err != nil {
		log.Info("Unmarshal failed", err)
		return nil, err
	}
	return pset, nil
}