// Copyright (c) 2017-2026 Lethean (https://lt.hn)
//
// Licensed under the European Union Public Licence (EUPL) version 1.2.
// SPDX-License-Identifier: EUPL-1.2

package blockchain

import (
	"context"
	"crypto/rand"
	"encoding/binary"
	"fmt"
	"net"
	"time"

	corelog "dappco.re/go/core/log"

	"dappco.re/go/core/blockchain/chain"
	"dappco.re/go/core/blockchain/config"
	"dappco.re/go/core/blockchain/p2p"
	levin "dappco.re/go/core/p2p/node/levin"
)

func runChainSyncLoop(ctx context.Context, blockchain *chain.Chain, chainConfig *config.ChainConfig, hardForks []config.HardFork, seedPeerAddress string) {
	opts := chain.SyncOptions{
		VerifySignatures: false,
		Forks:            hardForks,
	}

	for {
		select {
		case <-ctx.Done():
			return
		default:
		}

		if err := runChainSyncOnce(ctx, blockchain, chainConfig, opts, seedPeerAddress); err != nil {
			corelog.Warn("sync failed, retrying in 10s", "error", err, "seed", seedPeerAddress)
			select {
			case <-ctx.Done():
				return
			case <-time.After(10 * time.Second):
			}
			continue
		}

		select {
		case <-ctx.Done():
			return
		case <-time.After(30 * time.Second):
		}
	}
}

func runChainSyncOnce(ctx context.Context, blockchain *chain.Chain, chainConfig *config.ChainConfig, opts chain.SyncOptions, seedPeerAddress string) error {
	conn, err := net.DialTimeout("tcp", seedPeerAddress, 10*time.Second)
	if err != nil {
		return corelog.E("runChainSyncOnce", fmt.Sprintf("dial %s", seedPeerAddress), err)
	}
	defer conn.Close()

	p2pConn := levin.NewConnection(conn)

	var peerIDBytes [8]byte
	if _, err := rand.Read(peerIDBytes[:]); err != nil {
		return corelog.E("runChainSyncOnce", "generate peer id", err)
	}
	peerID := binary.LittleEndian.Uint64(peerIDBytes[:])

	localHeight, err := blockchain.Height()
	if err != nil {
		return corelog.E("runChainSyncOnce", "get local height", err)
	}

	handshakeRequest := p2p.HandshakeRequest{
		NodeData: p2p.NodeData{
			NetworkID: chainConfig.NetworkID,
			PeerID:    peerID,
			LocalTime: time.Now().Unix(),
			MyPort:    0,
		},
		PayloadData: p2p.CoreSyncData{
			CurrentHeight:  localHeight,
			ClientVersion:  config.ClientVersion,
			NonPruningMode: true,
		},
	}
	payload, err := p2p.EncodeHandshakeRequest(&handshakeRequest)
	if err != nil {
		return corelog.E("runChainSyncOnce", "encode handshake", err)
	}
	if err := p2pConn.WritePacket(p2p.CommandHandshake, payload, true); err != nil {
		return corelog.E("runChainSyncOnce", "write handshake", err)
	}

	packetHeader, packetData, err := p2pConn.ReadPacket()
	if err != nil {
		return corelog.E("runChainSyncOnce", "read handshake", err)
	}
	if packetHeader.Command != uint32(p2p.CommandHandshake) {
		return corelog.E("runChainSyncOnce", fmt.Sprintf("unexpected command %d", packetHeader.Command), nil)
	}

	var handshakeResponse p2p.HandshakeResponse
	if err := handshakeResponse.Decode(packetData); err != nil {
		return corelog.E("runChainSyncOnce", "decode handshake", err)
	}

	if err := p2p.ValidateHandshakeResponse(&handshakeResponse, chainConfig.NetworkID, chainConfig.IsTestnet); err != nil {
		return corelog.E("runChainSyncOnce", "validate handshake", err)
	}

	localSyncData := p2p.CoreSyncData{
		CurrentHeight:  localHeight,
		ClientVersion:  config.ClientVersion,
		NonPruningMode: true,
	}
	p2pConnection := chain.NewLevinP2PConn(p2pConn, handshakeResponse.PayloadData.CurrentHeight, localSyncData)

	return blockchain.P2PSync(ctx, p2pConnection, opts)
}
