package main

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

func main() {
	if len(os.Args) < 3 {
		log.Fatalf("Usage: %s <file> <pattern1> [<pattern2> ... <patternN>]\n", os.Args[0])
	}

	filename := os.Args[1]
	patterns := os.Args[2:]

	// Compile patterns into regular expressions
	regexPatterns := compilePatterns(patterns)

	// Read the file
	file, err := os.Open(filename)
	if err != nil {
		log.Fatalf("Error opening file: %s\n", err)
	}
	defer file.Close()

	var filteredLines []string
	var removedCount int

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		fmt.Printf("Processing line: %s\n", line) // Debug print
		if matchesAnyPattern(line, regexPatterns) {
			fmt.Printf("Line matches pattern, removing: %s\n", line) // Debug print
			removedCount++
		} else {
			filteredLines = append(filteredLines, line)
		}
	}

	if err := scanner.Err(); err != nil {
		log.Fatalf("Error reading file: %s\n", err)
	}

	// Write the filtered lines back to the file
	tempFile, err := os.CreateTemp("", "filtered_output")
	if err != nil {
		log.Fatalf("Error creating temporary file: %s\n", err)
	}
	defer os.Remove(tempFile.Name())

	for _, line := range filteredLines {
		_, err = tempFile.WriteString(line + "\n")
		if err != nil {
			log.Fatalf("Error writing to temporary file: %s\n", err)
		}
	}

	tempFile.Close()

	err = os.Rename(tempFile.Name(), filename)
	if err != nil {
		log.Fatalf("Error renaming temporary file: %s\n", err)
	}

	fmt.Printf("Filtered %d lines from %s\n", removedCount, filename)
}

func compilePatterns(patterns []string) []*regexp.Regexp {
	var regexPatterns []*regexp.Regexp
	for _, pattern := range patterns {
		// Convert wildcard pattern to regex pattern
		regexPattern := strings.ReplaceAll(regexp.QuoteMeta(pattern), "\\*", ".*")
		regexPattern = strings.TrimSuffix(regexPattern, `\.`)                    // Remove trailing dot if present
		fmt.Printf("Compiled pattern: %s to regex: %s\n", pattern, regexPattern) // Debug print
		re, err := regexp.Compile(regexPattern)
		if err != nil {
			log.Fatalf("Error compiling regex pattern: %s\n", err)
		}
		regexPatterns = append(regexPatterns, re)
	}
	return regexPatterns
}

func matchesAnyPattern(line string, patterns []*regexp.Regexp) bool {
	// Get the full path including directory
	parts := strings.Fields(line)
	if len(parts) < 2 {
		return false
	}
	fullPath := parts[1]
	fmt.Printf("Checking filename: %s against patterns\n", fullPath) // Debug print

	for _, pattern := range patterns {
		if pattern.MatchString(fullPath) {
			fmt.Printf("Pattern matched: %s in filename: %s\n", pattern.String(), fullPath) // Debug print
			return true
		}
	}
	return false
}
