package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
	"time"

	"github.com/getsentry/sentry-go"
)

func main() {
	var reader io.Reader
	var filePath string

	// Determine the source of input
	if len(os.Args) == 2 {
		// Read from the file specified in the argument
		filePath = os.Args[1]
		file, err := os.Open(filePath)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error opening file: %s\n", err)
			os.Exit(1)
		}
		defer file.Close()
		reader = file
	} else if len(os.Args) == 1 && !isInputFromPipe() {
		fmt.Fprintf(os.Stderr, "Usage: %s <path to log file> OR pipe input\n", os.Args[0])
		os.Exit(1)
	} else {
		// Read from stdin if data is being piped
		reader = os.Stdin
	}

	// Read content from the chosen input
	scanner := bufio.NewScanner(reader)
	var content strings.Builder
	for scanner.Scan() {
		content.WriteString(scanner.Text())
		content.WriteString("\n") // Preserve line breaks
	}

	if err := scanner.Err(); err != nil {
		fmt.Fprintf(os.Stderr, "Error reading input: %s\n", err)
		os.Exit(1)
	}

	logMessage := content.String()
	sendToSentry(logMessage)
}

// Helper function to check if there is data being piped to stdin
func isInputFromPipe() bool {
	fileInfo, err := os.Stdin.Stat()
	if err != nil {
		return false
	}
	return fileInfo.Mode()&os.ModeCharDevice == 0
}

// Function to handle sending data to Sentry
func sendToSentry(logMessage string) {
	dsn := os.Getenv("SENTRY_DSN")
	if dsn == "" {
		fmt.Fprintf(os.Stderr, "Error: SENTRY_DSN environment variable is not set.\n")
		os.Exit(1)
	}

	err := sentry.Init(sentry.ClientOptions{
		Dsn: dsn,
	})
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error initializing Sentry: %s\n", err)
		os.Exit(1)
	}

	defer func() {
		success := sentry.Flush(5 * time.Second)
		if !success {
			fmt.Fprintf(os.Stderr, "Failed to flush Sentry buffer within the expected time.\n")
		} else {
			fmt.Println("Sentry buffer flushed successfully.")
		}
	}()

	eventID := sentry.CaptureMessage(logMessage)
	if eventID != nil {
		fmt.Printf("Sent message to Sentry with event ID: %s\n", *eventID)
	} else {
		fmt.Fprintf(os.Stderr, "Failed to send message to Sentry.\n")
	}
}
