// Copyright 2025 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package downloader

import (
	"sync"

	"github.com/ethereum/go-ethereum/core/rawdb"
	"github.com/ethereum/go-ethereum/eth/ethconfig"
	"github.com/ethereum/go-ethereum/ethdb"
	"github.com/ethereum/go-ethereum/log"
)

// syncModer is responsible for managing the downloader's sync mode. It takes the
// user's preference at startup and then determines the appropriate sync mode
// based on the current chain status.
type syncModer struct {
	mode  ethconfig.SyncMode
	chain BlockChain
	disk  ethdb.KeyValueReader
	lock  sync.Mutex
}

func newSyncModer(mode ethconfig.SyncMode, chain BlockChain, disk ethdb.KeyValueReader) *syncModer {
	if mode == ethconfig.FullSync {
		// Phase C1: For XDC chains, never auto-switch to snap sync.
		// During bulk sync, state commits are optimized (skip for non-checkpoint blocks)
		// which means HasState() may return false. This is expected, not a corruption.
		// Force full sync mode to prevent the syncModer from switching.
		fullBlock := chain.CurrentBlock()
		if chain.HasState(fullBlock.Root) {
			log.Info("Enabled full-sync", "head", fullBlock.Number, "hash", fullBlock.Hash())
		} else {
			// State missing but user requested full sync — honor it.
			// XDC bulk sync will rebuild state from genesis.
			log.Warn("Full-sync enabled despite missing head state (XDC bulk sync will rebuild)",
				"head", fullBlock.Number, "hash", fullBlock.Hash())
		}
	} else {
		head := chain.CurrentBlock()
		if head.Number.Uint64() > 0 && chain.HasState(head.Root) {
			mode = ethconfig.FullSync
			log.Info("Switching from snap-sync to full-sync", "reason", "snap-sync complete")
		} else {
			// If snap sync was requested and our database is empty, grant it
			log.Info("Enabled snap-sync", "head", head.Number, "hash", head.Hash())
		}
	}
	return &syncModer{
		mode:  mode,
		chain: chain,
		disk:  disk,
	}
}

// get retrieves the current sync mode, either explicitly set, or derived
// from the chain status.
func (m *syncModer) get(report bool) ethconfig.SyncMode {
	m.lock.Lock()
	defer m.lock.Unlock()

	// If we're in snap sync mode, return that directly
	if m.mode == ethconfig.SnapSync {
		return ethconfig.SnapSync
	}
	logger := log.Debug
	if report {
		logger = log.Info
	}
	// We are probably in full sync, but we might have rewound to before the
	// snap sync pivot, check if we should re-enable snap sync.
	head := m.chain.CurrentBlock()
	if pivot := rawdb.ReadLastPivotNumber(m.disk); pivot != nil {
		if head.Number.Uint64() < *pivot {
			logger("Reenabled snap-sync as chain is lagging behind the pivot", "head", head.Number, "pivot", pivot)
			return ethconfig.SnapSync
		}
	}
	// Phase C1: Don't auto-switch to snap sync when head state is missing.
	// XDC bulk sync skips state commits for non-checkpoint blocks, so
	// HasState() may return false. This is expected behavior, not corruption.
	if !m.chain.HasState(head.Root) {
		logger("Head state missing (expected during XDC bulk sync)", "head", head.Number)
		// Don't switch to snap sync — continue full sync
	}
	// Nope, we're really full syncing
	return ethconfig.FullSync
}

// disableSnap disables the snap sync mode, usually it's called after a successful snap sync.
func (m *syncModer) disableSnap() {
	m.lock.Lock()
	m.mode = ethconfig.FullSync
	m.lock.Unlock()
}
