// Licensed to Apache Software Foundation (ASF) under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Apache Software Foundation (ASF) licenses this file to you 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, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package property

import (
	"context"
	"errors"
	"fmt"
	"path"
	"path/filepath"
	"time"

	"github.com/robfig/cron/v3"
	"github.com/spf13/pflag"
	"go.uber.org/multierr"

	"github.com/apache/skywalking-banyandb/api/common"
	"github.com/apache/skywalking-banyandb/api/data"
	commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
	databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
	"github.com/apache/skywalking-banyandb/banyand/internal/storage"
	"github.com/apache/skywalking-banyandb/banyand/metadata"
	"github.com/apache/skywalking-banyandb/banyand/metadata/schema"
	"github.com/apache/skywalking-banyandb/banyand/observability"
	obsservice "github.com/apache/skywalking-banyandb/banyand/observability/services"
	"github.com/apache/skywalking-banyandb/banyand/property/db"
	"github.com/apache/skywalking-banyandb/banyand/property/gossip"
	"github.com/apache/skywalking-banyandb/banyand/protector"
	"github.com/apache/skywalking-banyandb/banyand/queue"
	"github.com/apache/skywalking-banyandb/pkg/bus"
	"github.com/apache/skywalking-banyandb/pkg/fs"
	"github.com/apache/skywalking-banyandb/pkg/logger"
	banyandbpath "github.com/apache/skywalking-banyandb/pkg/path"
	"github.com/apache/skywalking-banyandb/pkg/run"
)

const (
	defaultFlushTimeout = 5 * time.Second
)

var (
	errEmptyRootPath         = errors.New("root path is empty")
	_                Service = (*service)(nil)
)

type service struct {
	metadata                 metadata.Repo
	pipeline                 queue.Server
	gossipMessenger          gossip.Messenger
	omr                      observability.MetricsRegistry
	lfs                      fs.FileSystem
	pm                       protector.Memory
	db                       db.Database
	closer                   *run.Closer
	l                        *logger.Logger
	repairScheduler          *repairScheduler
	snapshotDir              string
	root                     string
	repairDir                string
	repairBuildTreeCron      string
	repairTriggerCron        string
	nodeID                   string
	repairQuickBuildTreeTime time.Duration
	expireTimeout            time.Duration
	flushTimeout             time.Duration
	repairTreeSlotCount      int
	maxDiskUsagePercent      int
	maxFileSnapshotNum       int
	minFileSnapshotAge       time.Duration
	repairEnabled            bool
}

func (s *service) FlagSet() *run.FlagSet {
	flagS := run.NewFlagSet("storage")
	flagS.StringVar(&s.root, "property-root-path", "/tmp", "the root path of database")
	flagS.DurationVar(&s.flushTimeout, "property-flush-timeout", defaultFlushTimeout, "the memory data timeout of measure")
	flagS.IntVar(&s.maxDiskUsagePercent, "property-max-disk-usage-percent", 95, "the maximum disk usage percentage allowed")
	flagS.IntVar(&s.maxFileSnapshotNum, "property-max-file-snapshot-num", 10, "the maximum number of file snapshots allowed")
	flagS.DurationVar(&s.minFileSnapshotAge, "property-min-file-snapshot-age", time.Hour, "the minimum age for file snapshots to be eligible for deletion")
	flagS.DurationVar(&s.expireTimeout, "property-expire-delete-timeout", time.Hour*24*7, "the duration of the expired data needs to be deleted")
	flagS.IntVar(&s.repairTreeSlotCount, "property-repair-tree-slot-count", 32, "the slot count of the repair tree")
	flagS.StringVar(&s.repairBuildTreeCron, "property-repair-build-tree-cron", "@every 1h", "the cron expression for repairing the build tree")
	flagS.DurationVar(&s.repairQuickBuildTreeTime, "property-repair-quick-build-tree-time", time.Minute*10,
		"the duration of the quick build tree after operate the property")
	flagS.StringVar(&s.repairTriggerCron, "property-repair-trigger-cron", "0 2 * * *", "the cron expression for background repairing the property data")
	flagS.BoolVar(&s.repairEnabled, "property-repair-enabled", true, "whether to enable the background property repair")
	s.gossipMessenger.FlagSet().VisitAll(func(f *pflag.Flag) {
		flagS.AddFlag(f)
	})
	return flagS
}

func (s *service) Validate() error {
	if s.root == "" {
		return errEmptyRootPath
	}
	if s.maxDiskUsagePercent < 0 {
		return errors.New("property-max-disk-usage-percent must be greater than or equal to 0")
	}
	if s.maxDiskUsagePercent > 100 {
		return errors.New("property-max-disk-usage-percent must be less than or equal to 100")
	}
	_, err := cron.ParseStandard(s.repairBuildTreeCron)
	if err != nil {
		return errors.New("property-repair-build-tree-cron is not a valid cron expression")
	}
	if err = s.gossipMessenger.Validate(); err != nil {
		return fmt.Errorf("gossip vilidate failure: %w", err)
	}
	return nil
}

func (s *service) Name() string {
	return "property"
}

func (s *service) Role() databasev1.Role {
	return databasev1.Role_ROLE_DATA
}

func (s *service) PreRun(ctx context.Context) error {
	s.l = logger.GetLogger(s.Name())
	s.lfs = fs.NewLocalFileSystemWithLoggerAndLimit(s.l, s.pm.GetLimit())
	var err error
	s.root, err = banyandbpath.Get(s.root)
	if err != nil {
		return err
	}
	path := path.Join(s.root, s.Name())
	s.snapshotDir = filepath.Join(path, storage.SnapshotsDir)
	s.repairDir = filepath.Join(path, storage.RepairDir)
	obsservice.UpdatePath(path)
	val := ctx.Value(common.ContextNodeKey)
	if val == nil {
		return errors.New("node id is empty")
	}
	node := val.(common.Node)
	s.nodeID = node.NodeID

	snapshotLis := &snapshotListener{s: s}
	s.db, err = db.OpenDB(ctx, db.Config{
		Location:               filepath.Join(path, storage.DataDir),
		MetricsScopeName:       "property",
		FlushInterval:          s.flushTimeout,
		ExpireToDeleteDuration: s.expireTimeout,
		Repair: db.RepairConfig{
			Enabled:            s.repairEnabled,
			Location:           s.repairDir,
			BuildTreeCron:      s.repairBuildTreeCron,
			QuickBuildTreeTime: s.repairQuickBuildTreeTime,
			TreeSlotCount:      s.repairTreeSlotCount,
		},
		Index: db.IndexConfig{
			BatchWaitSec:       0,
			WaitForPersistence: true,
		},
		Snapshot: db.SnapshotConfig{
			Location: s.snapshotDir,
			Func: func(ctx context.Context) (string, error) {
				res := snapshotLis.Rev(ctx,
					bus.NewMessage(bus.MessageID(time.Now().UnixNano()), []*databasev1.SnapshotRequest_Group{}))
				snpMsg := res.Data().(*databasev1.Snapshot)
				if snpMsg.Error != "" {
					return "", errors.New(snpMsg.Error)
				}
				return filepath.Join(snapshotLis.s.snapshotDir, snpMsg.Name, storage.DataDir), nil
			},
		},
	}, s.omr, s.lfs)
	if err != nil {
		return err
	}

	// if the gossip address is empty or repair scheduler is not start, it means that the gossip is not enabled.
	if node.PropertyGossipGrpcAddress == "" || !s.repairEnabled {
		s.gossipMessenger = nil
	}
	if s.gossipMessenger != nil {
		if err = s.gossipMessenger.PreRun(ctx); err != nil {
			return err
		}
		s.db.RegisterGossip(s.gossipMessenger)

		// nolint:contextcheck
		scheduler, err := newRepairScheduler(s.closer.Ctx(), s.l, s.repairTriggerCron, s.metadata, s.gossipMessenger)
		if err != nil {
			return err
		}
		s.repairScheduler = scheduler
	}
	s.metadata.RegisterHandler("property", schema.KindGroup, &propertyGroupEventHandler{svc: s})
	return multierr.Combine(
		s.pipeline.Subscribe(data.TopicPropertyUpdate, &updateListener{s: s, l: s.l, path: path, maxDiskUsagePercent: s.maxDiskUsagePercent}),
		s.pipeline.Subscribe(data.TopicPropertyDelete, &deleteListener{s: s}),
		s.pipeline.Subscribe(data.TopicPropertyQuery, &queryListener{s: s}),
		s.pipeline.Subscribe(data.TopicSnapshot, snapshotLis),
		s.pipeline.Subscribe(data.TopicPropertyRepair, &repairListener{s: s}),
	)
}

type propertyGroupEventHandler struct {
	svc *service
}

func (h *propertyGroupEventHandler) OnInit([]schema.Kind) (bool, []int64) {
	return false, nil
}

func (h *propertyGroupEventHandler) OnAddOrUpdate(_ schema.Metadata) {}

func (h *propertyGroupEventHandler) OnDelete(md schema.Metadata) {
	if md.Kind != schema.KindGroup {
		return
	}
	group := md.Spec.(*commonv1.Group)
	if group.Catalog != commonv1.Catalog_CATALOG_PROPERTY {
		return
	}
	groupName := group.Metadata.GetName()
	if dropErr := h.svc.db.Drop(groupName); dropErr != nil {
		h.svc.l.Error().Err(dropErr).Str("group", groupName).Msg("failed to drop group")
	}
}

func (s *service) Serve() run.StopNotify {
	if s.gossipMessenger != nil {
		s.gossipMessenger.Serve(s.closer)
	}
	return s.closer.CloseNotify()
}

func (s *service) GracefulStop() {
	if s.repairScheduler != nil {
		s.repairScheduler.close()
	}
	if s.gossipMessenger != nil {
		s.gossipMessenger.GracefulStop()
	}
	s.closer.CloseThenWait()
	err := s.db.Close()
	if err != nil {
		s.l.Err(err).Msg("Fail to close the property module")
	}
}

func (s *service) GetGossIPGrpcPort() *uint32 {
	return s.gossipMessenger.GetServerPort()
}

// GetRouteTable implements RouteTableProvider interface by delegating to gossipMessenger.
func (s *service) GetRouteTable() *databasev1.RouteTable {
	if s.gossipMessenger == nil {
		return nil
	}
	return s.gossipMessenger.GetRouteTable()
}

// NewService returns a new service.
func NewService(metadata metadata.Repo, pipeline queue.Server, pipelineClient queue.Client,
	omr observability.MetricsRegistry, pm protector.Memory,
) (Service, error) {
	return &service{
		metadata: metadata,
		pipeline: pipeline,
		omr:      omr,
		pm:       pm,
		closer:   run.NewCloser(0),

		gossipMessenger: gossip.NewMessenger("property-repair",
			func(n *databasev1.Node) string { return n.PropertyRepairGossipGrpcAddress },
			omr, metadata, pipelineClient, 17932),
	}, nil
}
