package issue

import (
	"fmt"
	"os"
	"regexp"
	"strings"
	"time"

	"code.gitea.io/sdk/gitea"
	"github.com/jedib0t/go-pretty/v6/table"
)

func FromGiteas(is []*gitea.Issue, mindur time.Duration) []Issue {
	issues := make([]Issue, 0, len(is))

	for _, i := range is {
		if i == nil {
			continue
		}
		issue := FromGitea(*i)

		if issue.Duration < mindur {
			continue
		}

		issues = append(issues, issue)
	}
	return issues
}

func FromGitea(i gitea.Issue) Issue {
	issue := Issue{Issue: i}

	issue.Duration, _ = ExtractDuration(i.Body)

	return issue
}

func ExtractDuration(text string) (duration time.Duration, err error) {
	// First capture only the content inside ```info ... ```
	reBlock := regexp.MustCompile("(?s)```info(.*?)```")
	block := reBlock.FindStringSubmatch(text)
	if len(block) < 2 {
		err = fmt.Errorf("no info block found")
		return
	}

	// Now extract the duration line from inside that block
	reDuration := regexp.MustCompile(`duration:\s*([0-9hmin\s]+)`)
	match := reDuration.FindStringSubmatch(block[1])
	if len(match) < 2 {
		err = fmt.Errorf("no duration found inside info block")
		return
	}
	dur := strings.TrimSpace(match[1])
	dur = strings.ReplaceAll(dur, "min", "m")
	dur = strings.ReplaceAll(dur, " ", "") // remove spaces

	return time.ParseDuration(dur)
}

func Print(issues []Issue) {
	t := table.NewWriter()
	t.SetOutputMirror(os.Stdout)
	t.AppendHeader(table.Row{"#", "Title", "Body", "Duration", "Finished by"})

	for i, iss := range issues {
		if i != 0 {
			t.AppendSeparator()
		}
		t.AppendRow(table.Row{iss.Index, iss.Title, iss.Body, iss.Duration, iss.Closed})
	}

	t.Render()
}
