package healthcheck

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
)

// getChecksum calculates the SHA-256 checksum of a file
func getChecksum(filePath string) (string, error) {
	// Open the file
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	// Calculate SHA-256
	hash := sha256.New()
	if _, err := io.Copy(hash, file); err != nil {
		return "", err
	}

	return hex.EncodeToString(hash.Sum(nil)), nil
}

// checkFileChecksum checks if a single file's checksum matches the expected value
func checkFileChecksum(rootDir, fileName, expectedChecksum string) (bool, string) {
	filePath := filepath.Join(rootDir, strings.TrimSpace(fileName))
	actualChecksum, err := getChecksum(filePath)
	if err != nil {
		return false, fmt.Sprintf("Error reading file %s: %v", filePath, err)
	}

	if actualChecksum == expectedChecksum {
		return true, "" // fmt.Sprintf("Checksum for %s passed!", filePath)
	} else {
		return false, fmt.Sprintf("Checksum for %s failed. Expected %s, but got %s. Please revert your changes or contact the teaching team if you have a valid reason for adjusting them.", filePath, expectedChecksum, actualChecksum)
	}
}

func VerifyFiles(rootDir string, checkFileNameList string, checkFileSumList string) error {
	// Parse command-line arguments
	// checkFileNameList := flag.String("checkFileNameList", "", "Comma-separated list of files to check.")
	// checkFileSumList := flag.String("checkFileSumList", "", "Comma-separated list of expected checksums.")
	// rootDir := flag.String("rootDir", ".", "Root directory containing the files.")
	// flag.Parse()
	// Process input file names and checksums
	if len(checkFileNameList) == 0 {
		return nil // fmt.Errorf("No checksum happened")
		os.Exit(1)
	}
	fileNames := strings.Split(checkFileNameList, ",")
	checkSums := strings.Split(checkFileSumList, ",")

	// Check if the number of files matches the number of checksums

	if len(fileNames) != len(checkSums) {
		return fmt.Errorf("Error: The number of files and checksums do not match.")
		os.Exit(1)
	}

	allPassed := true
	var errorMessages []string

	// Check each file's checksum
	for i, fileName := range fileNames {
		expectedChecksum := strings.TrimSpace(checkSums[i])
		passed, message := checkFileChecksum(rootDir, fileName, expectedChecksum)
		if message != "" {
			return fmt.Errorf(message)
		}
		if !passed {
			allPassed = false
			errorMessages = append(errorMessages, message)
		}
	}
	if allPassed {
		return nil // fmt.Errorf("Congratulations! All checksums passed!")
	} else {
		return fmt.Errorf("Some checksums failed. Please review the errors below:")
		for _, msg := range errorMessages {
			return fmt.Errorf(msg)
		}
		return fmt.Errorf("Please revert your changes or contact the teaching team if you have a valid reason for adjusting them.")
	}
	return nil
}