package contrib

import (
	"fmt"
	"os/exec"
	"runtime"

	"github.com/gitlink-org/gitlink-cli/shortcuts/common"
)

func Shortcuts() []*common.Shortcut {
	return []*common.Shortcut{
		{
			Name:        "report",
			Description: "Generate a contribution report with pie chart",
			Flags: []common.Flag{
				{Name: "output", Short: "o", Usage: "Output HTML file path", Default: "contrib-report.html"},
				{Name: "open", Usage: "Open browser after generating", Bool: true, Default: "true"},
			},
			Run: runReport,
		},
	}
}

func runReport(ctx *common.RuntimeContext) error {
	if err := ctx.ResolveOwnerRepo(); err != nil {
		return err
	}

	// 1. 获取贡献者列表（从 issue 和 PR 数据中提取）
	contributors, err := fetchContributors(ctx)
	if err != nil {
		return fmt.Errorf("fetch contributors: %w", err)
	}

	// 2. 计算加权贡献分数
	reportData := calculateScores(contributors, nil, nil)

	// 3. 生成 HTML 报告
	outputPath := ctx.Arg("output")
	if err := generateHTML(ctx.Owner, ctx.Repo, reportData, outputPath); err != nil {
		return fmt.Errorf("generate HTML: %w", err)
	}

	fmt.Printf("Report generated: %s\n", outputPath)

	// 4. 打开浏览器
	if ctx.Arg("open") != "false" {
		if err := openBrowser(outputPath); err != nil {
			fmt.Printf("Warning: failed to open browser: %v\n", err)
		}
	}

	return nil
}

// openBrowser 打开浏览器
func openBrowser(url string) error {
	var cmd *exec.Cmd
	switch runtime.GOOS {
	case "windows":
		cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
	case "darwin":
		cmd = exec.Command("open", url)
	default: // linux
		cmd = exec.Command("xdg-open", url)
	}
	return cmd.Start()
}
