package ted

import (
	"bytes"
	"encoding/csv"
	"fmt"
	"io"
	"net/http"
	"strings"
)

const (
	calendarUrl = "%s/en/release-calendar/-/download/file/CSV/%d"
)

// Get OJS Number
func GetOJS(baseURL string, year int, date string, client *http.Client) (string, error) {
	var (
		ojs string
	)
	url := fmt.Sprintf(calendarUrl, baseURL, year)

	resp, err := client.Get(url)
	if err != nil {
		return ojs, err
	}
	defer resp.Body.Close()

	// read CSV
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return ojs, err
	}

	reader := csv.NewReader(bytes.NewReader(body))
	records, err := reader.ReadAll()
	if err != nil {
		return ojs, err
	}

	if len(records) < 2 {
		return ojs, fmt.Errorf("ojs calendar is empty")
	}

	for _, row := range records[1:] {
		rowDate := strings.TrimSpace(row[1])
		if rowDate == strings.TrimSpace(date) {
			// Format: YEAR + zero-padded OJS number to make total length 9 digits
			// Examples: 202500004, 202500014, 202500196
			ojs = fmt.Sprintf("%d%05s", year, strings.TrimSpace(fmt.Sprint(row[0])))
			break
		}
	}
	if ojs == "" {
		return ojs, fmt.Errorf("can not find ojs number")
	}

	return ojs, nil
}
