// 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 cmd

import (
	"encoding/csv"
	"os"
	"strings"

	lc "github.com/pingcap-inc/rule-engine/log/config"
	"github.com/spf13/cobra"
)

func newExportCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "export-rule",
		Short: "export rules as CSV",
		RunE: func(cmd *cobra.Command, args []string) error {
			rs, err := lc.LoadBetaRuleSpec()
			if err != nil {
				return err
			}

			records := [][]string{{
				"输出症状", "关联 KB", "关联 Jira", "组件", "日志级别", "日志匹配正则",
			}}
			for _, rule := range rs.Rule {
				records = append(records, []string{
					rule.Symptom,
					strings.Join(rule.KB, ","),
					strings.Join(rule.Jira, ","),
					rule.Patterns.Component,
					rule.Patterns.Level,
					".*" + strings.Join(rule.Patterns.Message, ".*") + ".*",
				})
			}

			w := csv.NewWriter(os.Stdout)
			for _, record := range records {
				if err := w.Write(record); err != nil {
					return err
				}
			}
			w.Flush()

			if err := w.Error(); err != nil {
				return err
			}

			return nil
		},
	}

	return cmd
}
