package graph

import (
	
	
	
	
	
	
	
	

	

	amtypes 
	amhist 
	amhistgorm 
	am 
	
)

var (
	// ErrHistory is when a history graph operation fails.
	ErrHistory = errors.New("history graph error")
	// ErrHistoryParams is when a history action gets invalid params.
	ErrHistoryParams = errors.New("history params error")
	// ErrHistoryAction is when a history action is unknown.
	ErrHistoryAction = errors.New("history action error")
	// ErrMachineNotTracked is when a machine has no history (yet).
	ErrMachineNotTracked = errors.New("machine not tracked")
)

// HistoryGraph wraps a [Graph] with a sharded GORM history mirror. Each
// tracked machine gets a [rpc.NetworkMachine] and a GORM history tracer, all
// sharing [HistoryGraph.Cfg]. Clock updates from the graph are applied to the
// network machines, which emit transitions to their history tracers.
//
// Machines are distributed across [HistoryGraph.Dbs] shards using the least
// loaded shard at registration time. The databases and their connections are
// owned by the caller. A shard can be shared by many [HistoryGraph] instances.
type HistoryGraph struct {
	*Graph

	// Cfg is the history config shared by all machines.
	Cfg amhistgorm.Config
	// Dbs are the history database shards.
	Dbs []*gorm.DB

	ctx    context.Context
	onErr  func(err error)
	parent am.Api
	// ownPar is a private parent machine, disposed on Close.
	ownPar *am.Machine

	mx      sync.Mutex
	machs   map[string]*historyMach
	shardOf map[string]uint8
	// shardLen tracks the number of machines per shard, for new assignments.
	shardLen []int
	// gen cancels in-flight registrations on Remove and Clear.
	gen     map[string]uint64
	genSeq  uint64
	pending map[string]string
	// pendingClocks buffers the latest clocks of machines being registered.
	pendingClocks map[string]pendingClock

	regCh    chan trackReq
	regWg    sync.WaitGroup
	stop     chan struct{}
	stopOnce sync.Once
}

// pendingClock is the latest clock update of a machine being registered.
type pendingClock struct {
	mTime    am.Time
	qTick    uint64
	machTick uint32
}

// trackReq is a queued machine registration.
type trackReq struct {
	c     *Machine
	shard uint8
	gen   uint64
}

// HistoryGraphOpts configures a new [HistoryGraph].
type HistoryGraphOpts struct {
	// OnErr handles history errors. Defaults to [Graph.ParentMach.AddErr], or
	// [log/slog].
	OnErr func(err error)
	// Parent parents all history network machines. Defaults to
	// [Graph.ParentMach], or a private machine.
	Parent am.Api
}

// historyMach is a single machine's history mirror.
type historyMach struct {
	mx sync.Mutex

	netMach *rpc.NetworkMachine
	nmInt   *rpc.NetMachInternal
	mem     amhist.MemoryApi

	// hash is the schema hash of the mirrored machine.
	hash string
	// states is the number of state names of the mirrored machine.
	states int
	// shard is the history DB shard of the machine.
	shard uint8
}

// HistParams are the optional params of a history action.
type HistParams struct {
	// State is the state of the bool actions.
	State string
	// States is the state list of latest-activated / latest-deactivated.
	States am.S
	// Start is the start of the human time range of the bool actions and
	// find-latest.
	Start time.Time
	// End is the end of the human time range of the bool actions and
	// find-latest.
	End time.Time
	// Limit is the maximum number of find-latest records. Default: 100.
	Limit int
	// Query are the filters of find-latest.
	Query amhist.Query
}

// HistoryResp is the history payload of a machine.
type HistoryResp struct {
	// Action is the executed history action.
	Action amtypes.HistoryAction `json:"action"`
	// Machine is the machine ID.
	Machine string `json:"machine"`
	// Bool is the result of the bool actions.
	Bool bool `json:"bool,omitempty"`
	// State is the result of latest-activated / latest-deactivated.
	State string `json:"state,omitempty"`
	// Records is the result of find-latest.
	Records []*amhist.MemoryRecord `json:"records,omitempty"`
	// Record is the machine record of find-latest.
	Record *amhist.MachineRecord `json:"record,omitempty"`
}

// NewHistoryGraph wraps g with a sharded GORM history mirror and tracks all of
// its machines. Each db is migrated once and used as a history shard.
func (
	 *Graph,  []*gorm.DB,  amhistgorm.Config,  ...HistoryGraphOpts,
) (*HistoryGraph, error) {
	if  == nil {
		return nil, fmt.Errorf("%w: graph is nil", ErrHistory)
	}
	if len() == 0 {
		return nil, fmt.Errorf("%w: no dbs", ErrHistory)
	}
	if len() > 255 {
		return nil, fmt.Errorf("%w: too many shards: %d", ErrHistory, len())
	}
	for ,  := range  {
		if  == nil {
			return nil, fmt.Errorf("%w: db %d is nil", ErrHistory, )
		}
		if  := amhistgorm.Migrate();  != nil {
			return nil, fmt.Errorf("%w: migrate shard %d: %w", ErrHistory, , )
		}
	}

	 := &HistoryGraph{
		Graph:         ,
		Cfg:           ,
		Dbs:           ,
		ctx:           context.Background(),
		machs:         make(map[string]*historyMach),
		shardOf:       make(map[string]uint8),
		shardLen:      make([]int, len()),
		gen:           make(map[string]uint64),
		pending:       make(map[string]string),
		pendingClocks: make(map[string]pendingClock),
		regCh:         make(chan trackReq, 4096),
		stop:          make(chan struct{}),
	}
	// the db connections are shared by all machines
	.Cfg.KeepDb = true
	// the shards are migrated once above
	.Cfg.SkipMigrate = true
	if .ParentMach != nil {
		.ctx = .ParentMach.Context()
	}
	.onErr = func( error) {
		if .ParentMach != nil {
			.ParentMach.AddErr(, nil)
			return
		}
		slog.Error("history graph", "err", )
	}
	.parent = .ParentMach
	for ,  := range  {
		if .OnErr != nil {
			.onErr = .OnErr
		}
		if .Parent != nil {
			.parent = .Parent
		}
	}
	if .parent == nil {
		.ownPar = am.New(.ctx, nil, &am.Opts{Id: "history-graph"})
		.parent = .ownPar
	}

	.hist = 

	// one registration worker per shard, so sqlite writes don't serialize
	for range  {
		.regWg.Add(1)
		go .regLoop()
	}

	// track existing machines
	.loop.Lock()
	for ,  := range .Machines {
		.Track()
	}
	.loop.Unlock()

	return , nil
}

// Track starts mirroring a graph machine into the history. It's called by
// [Graph.AddMachine]. Re-tracking with the same schema hash is a no-op.
// Registration is asynchronous; [HistoryGraph.Update] calls made meanwhile are
// buffered and applied once the machine is registered.
func ( *HistoryGraph) ( *Machine) {
	if  == nil || .Serialized == nil {
		return
	}

	.mx.Lock()
	if  := .machs[.ID];  != nil && .hash == .SchemaHash {
		.mx.Unlock()
		return
	}
	if ,  := .pending[.ID];  &&  == .SchemaHash {
		.mx.Unlock()
		return
	}
	 := .assignShard(.ID)
	.genSeq++
	 := .genSeq
	.gen[.ID] = 
	.pending[.ID] = .SchemaHash
	.mx.Unlock()

	// Track may race with Close, don't enqueue after it
	select {
	case <-.stop:
		return
	default:
	}

	 := trackReq{c: .Clone(), shard: , gen: }
	select {
	case .regCh <- :
	case <-.stop:
	}
}

// assignShard returns the shard of a machine, assigning the least loaded one
// for new machines. The caller must hold [HistoryGraph.mx].
func ( *HistoryGraph) ( string) uint8 {
	if ,  := .shardOf[];  {
		return 
	}

	 := 0
	for  := 1;  < len(.shardLen); ++ {
		if .shardLen[] < .shardLen[] {
			 = 
		}
	}
	.shardOf[] = uint8()
	.shardLen[]++

	return uint8()
}

// regLoop registers queued machines until Close.
func ( *HistoryGraph) () {
	defer .regWg.Done()

	for {
		select {
		case <-.stop:
			return
		default:
		}

		select {
		case <-.stop:
			return
		case  := <-.regCh:
			.regMachine()
		}
	}
}

// regMachine creates the history mirror of a queued machine.
func ( *HistoryGraph) ( trackReq) {
	 := .c
	// netmachs require the schema to match the state names exactly
	 := normalizeSchema(.Schema, .StateNames)

	, ,  := rpc.NewNetworkMachine(.ctx, .ID, nil, ,
		.StateNames, .parent, nil, false)
	if  != nil {
		.regFailed(, fmt.Errorf("%w: %s: %w", ErrHistory, .ID, ))
		return
	}
	,  := amhistgorm.NewMemory(.ctx, .Dbs[.shard], ,
		.Cfg, .onErr)
	if  != nil {
		.Dispose()
		.regFailed(, )
		return
	}

	 := &historyMach{
		netMach: ,
		nmInt:   ,
		mem:     ,
		hash:    .SchemaHash,
		states:  len(.StateNames),
		shard:   .shard,
	}

	.mx.Lock()
	if .gen[.ID] != .gen {
		// removed or superseded while registering
		.mx.Unlock()
		_ = .Dispose()
		.Dispose()
		return
	}
	 := .machs[.ID]
	.machs[.ID] = 
	delete(.pending, .ID)
	,  := .pendingClocks[.ID]
	delete(.pendingClocks, .ID)
	.mx.Unlock()

	if  != nil {
		.dispose()
	}
	// record the latest clock, buffered while registering
	if  {
		.update(.mTime, .qTick, .machTick)
	} else if .MTimeSum > 0 {
		.update(.Time, .QueueTick, .MachineTick)
	}
}

// regFailed reports a failed registration and clears its pending entry.
func ( *HistoryGraph) ( trackReq,  error) {
	.mx.Lock()
	if .gen[.c.ID] == .gen {
		delete(.pending, .c.ID)
		delete(.pendingClocks, .c.ID)
	}
	.mx.Unlock()

	.onErr()
}

// Update applies the current clocks of a machine to its history mirror. It's a
// no-op for machines which aren't tracked. Updates of machines being
// registered are buffered and applied after registration.
func ( *HistoryGraph) (
	 string,  am.Time,  uint64,  uint32,
) {
	.mx.Lock()
	// buffer for a pending registration, including schema changes
	,  := .pending[]
	if  := .machs[];  != nil && ! {
		.mx.Unlock()
		.update(, , )
		return
	}
	if ,  := .gen[];  {
		.pendingClocks[] = pendingClock{
			mTime:    slices.Clone(),
			qTick:    ,
			machTick: ,
		}
	}
	.mx.Unlock()
}

// Remove stops mirroring a machine and disposes its history.
func ( *HistoryGraph) ( string) {
	.mx.Lock()
	// cancel in-flight registrations
	delete(.gen, )
	delete(.pending, )
	delete(.pendingClocks, )

	 := .machs[]
	delete(.machs, )
	if ,  := .shardOf[];  {
		delete(.shardOf, )
		.shardLen[]--
	}
	.mx.Unlock()

	if  != nil {
		.dispose()
	}
}

// ShardCounts returns the number of machines assigned to each history shard.
func ( *HistoryGraph) () []int {
	.mx.Lock()
	defer .mx.Unlock()

	return slices.Clone(.shardLen)
}

// TrackedCount returns the number of machines with a registered history.
func ( *HistoryGraph) () int {
	.mx.Lock()
	defer .mx.Unlock()

	return len(.machs)
}

// ShardOf returns the history shard of a machine.
func ( *HistoryGraph) ( string) (uint8, bool) {
	.mx.Lock()
	defer .mx.Unlock()

	if  := .machs[];  != nil {
		return .shard, true
	}
	,  := .shardOf[]
	return , 
}

// History runs a history API method of a tracked machine.
func ( *HistoryGraph) (
	 context.Context,  string,  amtypes.HistoryAction,  HistParams,
) (*HistoryResp, error) {
	.mx.Lock()
	 := .machs[]
	.mx.Unlock()

	if  == nil {
		return nil, fmt.Errorf("%w: %s", ErrMachineNotTracked, )
	}

	 := &HistoryResp{Action: , Machine: }
	 := .mem

	switch  {
	case amtypes.HistActivatedBetween, amtypes.HistActiveBetween,
		amtypes.HistDeactivatedBetween, amtypes.HistInactiveBetween:

		if .State == "" {
			return nil, fmt.Errorf("%w: state is required", ErrHistoryParams)
		}
		switch  {
		case amtypes.HistActivatedBetween:
			.Bool = .ActivatedBetween(, .State, .Start, .End)
		case amtypes.HistActiveBetween:
			.Bool = .ActiveBetween(, .State, .Start, .End)
		case amtypes.HistDeactivatedBetween:
			.Bool = .DeactivatedBetween(, .State, .Start, .End)
		case amtypes.HistInactiveBetween:
			.Bool = .InactiveBetween(, .State, .Start, .End)
		}

	case amtypes.HistLatestActivated, amtypes.HistLatestDeactivated:
		if len(.States) == 0 {
			return nil, fmt.Errorf("%w: states are required", ErrHistoryParams)
		}
		if  == amtypes.HistLatestActivated {
			.State = .LatestActivated(, .States...)
		} else {
			.State = .LatestDeactivated(, .States...)
		}

	case amtypes.HistFindLatest:
		// flush the queue, so fresh records are queryable
		if  := .Sync();  != nil {
			return nil, 
		}
		 := .Limit
		if  <= 0 {
			 = 100
		}
		,  := .FindLatest(, true, , .Query)
		if  != nil {
			return nil, 
		}
		.Records = 
		.Record = .MachineRecord()

	default:
		return nil, fmt.Errorf("%w: %s", ErrHistoryAction, .Value)
	}

	return , nil
}

// Close stops mirroring all machines. The databases are left open.
func ( *HistoryGraph) () error {
	// detach first, so no new machines get tracked
	.Graph.loop.Lock()
	if .Graph.hist ==  {
		.Graph.hist = nil
	}
	.Graph.loop.Unlock()

	.stopOnce.Do(func() { close(.stop) })
	.regWg.Wait()
	.clearAll()

	if .ownPar != nil {
		.ownPar.Dispose()
		.ownPar = nil
	}

	return nil
}

// private

// clearAll stops mirroring all machines.
func ( *HistoryGraph) () {
	.mx.Lock()
	// cancel in-flight registrations
	clear(.gen)
	clear(.pending)
	clear(.pendingClocks)
	clear(.shardOf)
	for  := range .shardLen {
		.shardLen[] = 0
	}

	 := make([]*historyMach, 0, len(.machs))
	for ,  := range .machs {
		 = append(, )
		delete(.machs, )
	}
	.mx.Unlock()

	// dispose in parallel, the histories are independent
	 := make(chan struct{}, runtime.NumCPU())
	var  sync.WaitGroup
	for ,  := range  {
		.Add(1)
		 <- struct{}{}
		go func( *historyMach) {
			defer .Done()
			defer func() { <- }()
			.dispose()
		}()
	}
	.Wait()
}

// dispose disposes a machine's history and network machine. The history is
// disposed first, because the network machine runs its dispose handlers under
// a lock. The caller must not hold [HistoryGraph.mx].
func ( *HistoryGraph) ( *historyMach) {
	// wait for in-flight clock updates
	.mx.Lock()
	defer .mx.Unlock()

	_ = .mem.Dispose()
	.netMach.Dispose()
}

// update applies clocks to the network machine, which emits them to the
// history tracer.
func ( *historyMach) (
	 am.Time,  uint64,  uint32,
) {
	.mx.Lock()
	defer .mx.Unlock()

	if len() != .states {
		return
	}
	.nmInt.Lock()
	.nmInt.UpdateClock(slices.Clone(), , )
}

// normalizeSchema returns a schema matching the passed state names exactly,
// filling in missing states with empty definitions.
func normalizeSchema( am.Schema,  am.S) am.Schema {
	 := make(am.Schema, len())
	for ,  := range  {
		[] = []
	}

	return 
}