package main

import (
	"fmt"
	"log"
	"os"
	"strconv"

	"github.com/joho/godotenv"
	"mindforge.cronjob/internal/agent"
	"mindforge.cronjob/internal/git"
	"mindforge.cronjob/internal/message"
)

func main() {
	// Read "GIT_REPOSITORY" environment variable
	if err := godotenv.Load(); err != nil {
		log.Println("WARNING: No .env file found or error loading it")
	}

	gitRepo := os.Getenv("GIT_REPOSITORY")
	if gitRepo == "" {
		log.Println("WARNING: GIT_REPOSITORY environment variable is not set")
	} else {
		fmt.Printf("Starting Mindforge.Cronjob for repo: %s\n", gitRepo)
	}

	// Initialize services
	gitService := git.NewGitService()

	// Resolve how many top files to return (TOP_N_FILES env var, default 10)
	topN := 10
	if v := os.Getenv("TOP_N_FILES"); v != "" {
		if n, err := strconv.Atoi(v); err == nil && n > 0 {
			topN = n
		}
	}

	// Get modifications
	var modifications map[string]string
	error := gitService.FetchContents(gitRepo)
	if error != nil {
		log.Println("ERROR: Failed to fetch contents:", error)
	}

	// Resolve how many days to look back (LAST_N_DAYS env var, default 7)
	days := 7
	if v := os.Getenv("LAST_N_DAYS"); v != "" {
		if n, err := strconv.Atoi(v); err == nil && n > 0 {
			days = n
		}
	}

	modifications, error = gitService.GetModifications(days, topN)
	if error != nil {
		log.Println("ERROR: Failed to get modifications:", error)
	}

	fmt.Printf("Found %d modifications\n", len(modifications))

	for file, content := range modifications {
		fmt.Printf("Processing file: %s\n", file)

		raw_summary, err := agent.SummaryCreatorAgent(file, content)
		if err != nil {
			log.Println("ERROR: Failed to create summary:", err)
			continue
		}

		md_summary, err := agent.SummaryFormatterAgent(raw_summary)
		if err != nil {
			log.Println("ERROR: Failed to create markdown summary:", err)
			continue
		}

		fmt.Printf("Summary: %s\n", md_summary)

		err = message.SendDiscordNotification(file, md_summary)
		if err != nil {
			log.Println("ERROR: Failed to send Discord notification:", err)
		}
	}
}
