package main

import (
	"context"
	"dataservices/commons/config"
	"dataservices/commons/database"
	"dataservices/commons/metrics"
	"dataservices/commons/utils"
	"dataservices/worker"
	"flag"
	"fmt"

	"github.com/tidbcloud/tiinf/monitor/tilog"
	"github.com/tidbcloud/tiinf/monitor/titracing"
	"go.opentelemetry.io/otel"
	"go.uber.org/zap"
)

const (
	defaultConfigPath = "/etc/dbaas/config.yaml"
)

func runEtlHourJob(ctx context.Context, startDate string, endDate string) {
	tilog.Info(ctx, "date info", zap.String("startDate", startDate), zap.String("endDate", endDate))
	startTimestamp := utils.ConvertDateHourToTimestamp(startDate)
	endTimestamp := utils.ConvertDateHourToTimestamp(endDate)
	etlWorker := worker.NewEtlInstance(ctx)
	for tempTimestamp := startTimestamp; tempTimestamp <= endTimestamp; tempTimestamp += 3600 {
		etlWorker.RunEtlJobHourly(ctx, tempTimestamp, true)
	}
}

func runEtlDayJob(ctx context.Context, startDate string, endDate string) {
	tilog.Info(ctx, "date info", zap.String("startDate", startDate), zap.String("endDate", endDate))
	startTimestamp := utils.ConvertDateHourToTimestamp(startDate)
	endTimestamp := utils.ConvertDateHourToTimestamp(endDate)
	etlWorker := worker.NewEtlInstance(ctx)
	for tempTimestamp := startTimestamp; tempTimestamp <= endTimestamp; tempTimestamp += 86400 {
		etlWorker.RunEtlJobDaily(ctx, tempTimestamp)
	}
}

func main() {
	var configPath string
	var jobType string
	flag.StringVar(&configPath, "config_path", defaultConfigPath, "DBaaS configuration file path")
	flag.StringVar(&jobType, "job_type", "etl_day", "job type")
	// Job_etl param
	startDate := flag.String("start_date", utils.GetDiffDateHour(-7), "start_date")
	endDate := flag.String("end_date", utils.GetDiffDateHour(-1), "end_date")
	flag.Parse()

	ctx := context.TODO()
	if _, err := titracing.InitJaeger("etl-tools"); err != nil {
		tilog.Error(ctx, "init tiinf jaeger provider failed", zap.Error(err))
		panic(fmt.Sprintf("failed to init tracing, err=%v", err))
	}
	ctx, span := otel.Tracer("etl-tools").Start(context.TODO(), "etl-tools")
	defer span.End()

	tilog.Info(ctx, "etl worker begin run")
	// Load config
	err := config.InitConfig(configPath)
	if err != nil {
		// TODO: unexpected error like this, should we throw a alert/page, just log seems not enough ?
		tilog.Fatal(ctx, "Initialize configuration failed", zap.Error(err))
	}
	metrics.RegisterToolsMetrics()
	// Connect database
	config := config.Global()
	database.Connect(ctx,
		config.MysqlConf.User,
		config.MysqlConf.Password,
		config.MysqlConf.Host,
		config.MysqlConf.Port,
		config.MysqlConf.Database,
		config.MysqlConf.CharSet,
		config.MysqlConf.TimeZone,
	)
	switch jobType {
	case "etl_hour":
		runEtlHourJob(ctx, *startDate, *endDate)
	case "etl_day":
		runEtlDayJob(ctx, *startDate, *endDate)
	default:
		tilog.Fatal(ctx, "Unsupport job type", zap.String("jobtype", jobType))
	}
}
