package main

import (
	"fmt"
	"io"
	"log"
	"os"
	"strconv"
	"strings"

	"code.gitea.io/sdk/gitea"
)

func main() {
	token := os.Getenv("GITEA_TOKEN")
	baseURL := os.Getenv("GITEA_URL")
	repoFullName := os.Getenv("GITHUB_REPOSITORY")
	prNumberStr := os.Getenv("PR_NUMBER")

	if token == "" || repoFullName == "" || prNumberStr == "" {
		log.Fatal("Missing required environment variables: GITEA_TOKEN, GITHUB_REPOSITORY, PR_NUMBER")
	}

	if baseURL == "" {
		baseURL = "https://gitea.com"
	}

	prNumber, err := strconv.ParseInt(prNumberStr, 10, 64)
	if err != nil {
		log.Fatalf("Invalid PR_NUMBER: %v", err)
	}

	repoParts := strings.Split(repoFullName, "/")
	if len(repoParts) != 2 {
		log.Fatalf("Invalid GITHUB_REPOSITORY format: %s", repoFullName)
	}
	owner, repo := repoParts[0], repoParts[1]

	client, err := gitea.NewClient(baseURL, gitea.SetToken(token))
	if err != nil {
		log.Fatalf("Failed to create Gitea client: %v", err)
	}

	// Get PR files
	files, _, err := client.ListPullRequestFiles(owner, repo, prNumber, gitea.ListPullRequestFilesOptions{})
	if err != nil {
		log.Fatalf("Failed to get PR files: %v", err)
	}

	var counts []string
	for _, file := range files {
		if !strings.HasSuffix(file.Filename, ".md") {
			continue
		}

		fmt.Printf("Reviewing file: %s\n", file.Filename)
		content, err := readFile(file.Filename)
		if err != nil {
			fmt.Printf("Error reading file %s: %v\n", file.Filename, err)
			continue
		}

		count := countWords(content)
		counts = append(counts, fmt.Sprintf("#### Word count for `%s`\n\nWord count: %d", file.Filename, count))
	}

	if len(counts) > 0 {
		commentBody := "### 🤖 Word Count Report\n\n" + strings.Join(counts, "\n\n---\n\n")
		_, _, err = client.CreateIssueComment(owner, repo, prNumber, gitea.CreateIssueCommentOption{
			Body: commentBody,
		})
		if err != nil {
			log.Fatalf("Failed to post PR comment: %v", err)
		}
		fmt.Println("Successfully posted review comments.")
	} else {
		fmt.Println("No Markdown files to review or no suggestions found.")
	}
}

func readFile(path string) (string, error) {
	f, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer f.Close()

	content, err := io.ReadAll(f)
	if err != nil {
		return "", err
	}
	return string(content), nil
}

func countWords(text string) int {
	return len(strings.Fields(text))
}
