package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

// applyPrefModifications handles `t:pref` type patches
func applyPrefModifications(targetFilePath string, modifications []string) error {
	// Open the target file
	targetFile, err := os.Open(targetFilePath)
	if err != nil {
		return fmt.Errorf("failed to open target file: %v", err)
	}
	defer targetFile.Close()

	// Create a temporary file
	tempFilePath := targetFilePath + ".tmp"
	tempFile, err := os.Create(tempFilePath)
	if err != nil {
		return fmt.Errorf("failed to create temp file: %v", err)
	}
	defer tempFile.Close()

	// Parse modifications into a map for easy lookup
	modMap := make(map[string]string)
	for _, mod := range modifications {
		if strings.HasPrefix(mod, "+pref") {
			// Strip the `+` and extract the key within parentheses
			start := strings.Index(mod, "(")
			end := strings.LastIndex(mod, ")")
			if start > 0 && end > start {
				key := strings.TrimSpace(mod[start+1 : end]) // Extract the preference key
				modMap[key] = strings.TrimPrefix(mod, "+")   // Full modification line
			}
		}
	}

	scanner := bufio.NewScanner(targetFile)
	modifiedLines := map[string]bool{} // Tracks applied modifications

	// Process each line of the target file
	for scanner.Scan() {
		line := scanner.Text()
		lineModified := false

		// Check if the line matches any modification key
		for key, replacement := range modMap {
			if strings.Contains(line, key) && !modifiedLines[key] {
				// Write the replacement line
				fmt.Printf("Replacing line: %s\n", line)
				if _, err := tempFile.WriteString(replacement + "\n"); err != nil {
					return fmt.Errorf("failed to write to temp file: %v", err)
				}
				modifiedLines[key] = true
				lineModified = true
				break
			}
		}

		// Write the original line if no modification matches
		if !lineModified {
			if _, err := tempFile.WriteString(line + "\n"); err != nil {
				return fmt.Errorf("failed to write to temp file: %v", err)
			}
		}
	}

	if err := scanner.Err(); err != nil {
		return fmt.Errorf("failed to read target file: %v", err)
	}

	// Append remaining modifications that were not in the file
	for key, replacement := range modMap {
		if !modifiedLines[key] {
			fmt.Printf("Adding new preference: %s\n", replacement)
			if _, err := tempFile.WriteString(replacement + "\n"); err != nil {
				return fmt.Errorf("failed to append new preference to temp file: %v", err)
			}
		}
	}

	// Close the files to ensure proper cleanup
	tempFile.Close()
	targetFile.Close()

	// Replace the original file with the modified temp file
	if err := os.Rename(tempFilePath, targetFilePath); err != nil {
		return fmt.Errorf("failed to replace target file: %v", err)
	}

	fmt.Println("Preferences successfully modified.")
	return nil
}
