package main

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
)

// applyCopyPatch handles `t:copy` type patches for copying and replacing files or directories
func applyCopyPatch(inputPath, outputPath string) error {
	fmt.Printf("Copying from %s to %s\n", inputPath, outputPath)

	// Check if the source exists
	info, err := os.Stat(inputPath)
	if os.IsNotExist(err) {
		return fmt.Errorf("input path does not exist: %s", inputPath)
	}

	// Handle files and directories differently
	if info.IsDir() {
		// Copy a directory
		return copyDirectory(inputPath, outputPath)
	} else {
		// Copy a single file
		return copyFile(inputPath, outputPath, info.Mode())
	}
}

// copyFile copies a single file and replaces the destination if it exists
func copyFile(srcFilePath, dstFilePath string, fileMode os.FileMode) error {
	// Ensure the destination directory exists
	destDir := filepath.Dir(dstFilePath)
	if err := os.MkdirAll(destDir, os.ModePerm); err != nil {
		return fmt.Errorf("failed to create destination directory: %s", destDir)
	}

	// Open source file
	srcFile, err := os.Open(srcFilePath)
	if err != nil {
		return fmt.Errorf("failed to open source file: %s", srcFilePath)
	}
	defer srcFile.Close()

	// Create destination file
	dstFile, err := os.Create(dstFilePath)
	if err != nil {
		return fmt.Errorf("failed to create destination file: %s", dstFilePath)
	}
	defer dstFile.Close()

	// Copy contents from source to destination
	if _, err := io.Copy(dstFile, srcFile); err != nil {
		return fmt.Errorf("failed to copy file: %v", err)
	}

	// Set file permissions
	if err := os.Chmod(dstFilePath, fileMode); err != nil {
		return fmt.Errorf("failed to set file permissions: %v", err)
	}

	fmt.Printf("File copied: %s -> %s\n", srcFilePath, dstFilePath)
	return nil
}

// copyDirectory copies the contents of a directory and replaces the destination if it exists
func copyDirectory(srcDirPath, dstDirPath string) error {
	// Ensure the destination directory exists
	if err := os.MkdirAll(dstDirPath, os.ModePerm); err != nil {
		return fmt.Errorf("failed to create destination directory: %s", dstDirPath)
	}

	// Walk through the directory and copy each file/directory
	return filepath.Walk(srcDirPath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		// Compute the destination path
		relPath, err := filepath.Rel(srcDirPath, path)
		if err != nil {
			return fmt.Errorf("failed to compute relative path: %v", err)
		}
		destPath := filepath.Join(dstDirPath, relPath)

		if info.IsDir() {
			// Create the destination directory
			if err := os.MkdirAll(destPath, os.ModePerm); err != nil {
				return fmt.Errorf("failed to create directory: %s", destPath)
			}
		} else {
			// Copy the file
			if err := copyFile(path, destPath, info.Mode()); err != nil {
				return err
			}
		}
		return nil
	})
}