// cron — 驗證 cron expression 格式，回傳 cron_id
// 實際排程由 Cypher Executor 負責
//
//go:build tinygo

package main

import (
	"encoding/json"
	"io"
	"os"
	"strconv"
	"strings"
	"time"
)

type Input struct {
	CronExpr    string `json:"cron_expr"`
	Description string `json:"description"`
}

func main() {
	raw, err := io.ReadAll(os.Stdin)
	if err != nil {
		writeError("failed to read stdin: " + err.Error())
		return
	}
	var input Input
	if err := json.Unmarshal(raw, &input); err != nil {
		writeError("invalid input JSON: " + err.Error())
		return
	}
	if input.CronExpr == "" {
		writeError("cron_expr 必填")
		return
	}

	if err := validateCronExpr(input.CronExpr); err != nil {
		writeError("無效的 cron expression: " + err.Error())
		return
	}

	cronID := "cron-" + strconv.FormatInt(time.Now().UnixNano()/1e6, 10)

	out, _ := json.Marshal(map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"cron_id":     cronID,
			"cron_expr":   input.CronExpr,
			"enabled":     true,
			"description": input.Description,
		},
	})
	os.Stdout.Write(out)
}

// validateCronExpr — 驗證標準 5 欄位 cron expression
func validateCronExpr(expr string) error {
	fields := strings.Fields(expr)
	if len(fields) != 5 {
		return &cronError{"需要 5 個欄位（分 時 日 月 週），實際: " + strconv.Itoa(len(fields))}
	}

	// 各欄位範圍: 分(0-59), 時(0-23), 日(1-31), 月(1-12), 週(0-7)
	ranges := [][2]int{{0, 59}, {0, 23}, {1, 31}, {1, 12}, {0, 7}}
	names := []string{"分鐘", "小時", "日", "月", "星期"}

	for i, field := range fields {
		if err := validateCronField(field, ranges[i][0], ranges[i][1], names[i]); err != nil {
			return err
		}
	}
	return nil
}

func validateCronField(field string, min, max int, name string) error {
	if field == "*" {
		return nil
	}
	// 支援 */n 格式
	if strings.HasPrefix(field, "*/") {
		n, err := strconv.Atoi(field[2:])
		if err != nil || n <= 0 {
			return &cronError{name + " 步進值無效: " + field}
		}
		return nil
	}
	// 支援 a-b 範圍
	if strings.Contains(field, "-") {
		parts := strings.SplitN(field, "-", 2)
		a, err1 := strconv.Atoi(parts[0])
		b, err2 := strconv.Atoi(parts[1])
		if err1 != nil || err2 != nil || a < min || b > max || a > b {
			return &cronError{name + " 範圍無效: " + field}
		}
		return nil
	}
	// 支援逗號分隔
	if strings.Contains(field, ",") {
		for _, part := range strings.Split(field, ",") {
			n, err := strconv.Atoi(part)
			if err != nil || n < min || n > max {
				return &cronError{name + " 值無效: " + part}
			}
		}
		return nil
	}
	// 單一數字
	n, err := strconv.Atoi(field)
	if err != nil || n < min || n > max {
		return &cronError{name + " 值超出範圍 [" + strconv.Itoa(min) + "-" + strconv.Itoa(max) + "]: " + field}
	}
	return nil
}

type cronError struct{ msg string }

func (e *cronError) Error() string { return e.msg }

func writeError(msg string) {
	out, _ := json.Marshal(map[string]interface{}{"success": false, "error": msg})
	os.Stdout.Write(out)
}
