package brc20

import (
	"bytes"
	"encoding/hex"
	"encoding/json"

	"github.com/btcsuite/btcd/btcutil"
	"github.com/btcsuite/btcd/chaincfg"
	"github.com/btcsuite/btcd/txscript"
	"github.com/btcsuite/btcd/wire"
)

type BRC20Transfer struct {
	Protocol  string `json:"p"`
	Operation string `json:"op"`
	Ticker    string `json:"tick"`
	Amount    uint64 `json:"amt"`
}

func CreateUnsignedBRC20Tx(netParams *chaincfg.Params, sender string, receiver string, ticker string, amount uint64) (*wire.MsgTx, error) {
	// 1. 构造BRC-20转移JSON数据
	transferData := BRC20Transfer{
		Protocol:  "brc-20",
		Operation: "transfer",
		Ticker:    ticker,
		Amount:    amount,
	}
	jsonData, _ := json.Marshal(transferData)

	// 2. 创建基础交易结构
	tx := wire.NewMsgTx(wire.TxVersion)

	// 3. 添加OP_RETURN输出（铭文数据）
	opReturnScript, _ := txscript.NullDataScript(jsonData)
	tx.AddTxOut(wire.NewTxOut(0, opReturnScript)) // 0 satoshi输出

	// 4. 添加接收方输出
	receiverAddr, _ := btcutil.DecodeAddress(receiver, netParams)
	receiverScript, _ := txscript.PayToAddrScript(receiverAddr)
	tx.AddTxOut(wire.NewTxOut(int64(amount), receiverScript)) // 示例1000 satoshi

	return tx, nil
}

func IsInscriptionScript(scriptHex string) bool {
	// 解码十六进制脚本
	script, err := hex.DecodeString(scriptHex)
	if err != nil || len(script) < 20 {
		return false
	}

	// 检查起始标记 OP_FALSE OP_IF (0063)
	if !bytes.HasPrefix(script, []byte{0x00, 0x63}) {
		return false
	}

	// 检查协议标识 "ord"
	ordPos := bytes.Index(script, []byte("ord"))
	if ordPos == -1 || ordPos > 10 {
		return false
	}

	// 检查内容类型声明
	contentTypePos := ordPos + 3
	if contentTypePos >= len(script) {
		return false
	}

	// 验证数据包裹结构
	if !bytes.Contains(script, []byte{0x00}) || // OP_0
		!bytes.HasSuffix(script, []byte{0x68}) { // OP_ENDIF
		return false
	}

	return true
}
