// Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package config

import (
	_ "embed"
	"fmt"
	"github.com/BurntSushi/toml"
	"time"
)

//go:embed rule.toml
var ruleStr string

type RuleItem struct {
	ID          int64            `toml:"id"`
	Symptom     string           `toml:"symptom"`
	Description string           `toml:"description"`
	KB          []string         `toml:"kb"`
	Jira        []string         `toml:"jira"`
	Version     string           `toml:"version"`
	Patterns    SlowQueryPattern `toml:"patterns"`
}

func (rule *RuleItem) BuildQuery(beginT, endT time.Time) (string,error) {
	filledQuery := fmt.Sprintf(rule.Patterns.Query, beginT.UnixNano()/1000000, endT.UnixNano()/1000000)
	return filledQuery, nil
}

type SlowQueryPattern struct {
	Query string `toml:"query"`
}

type RuleSpec struct {
	Rule []RuleItem `yaml:"rule" toml:"rule"`
}

func LoadBetaRuleSpec() (*RuleSpec, error) {
	ruleSpec := &RuleSpec{Rule: []RuleItem{}}
	if _, err := toml.Decode(ruleStr, ruleSpec); err != nil {
		return nil, err
	}
	return ruleSpec, nil
}
