package mloco

import (
	"encoding/hex"
	"fmt"
)

// HexToBSON decodes a hex-encoded BSON document into a comparable map.
func HexToBSON(hexStr string) (map[string]any, error) {
	raw, err := hex.DecodeString(hexStr)
	if err != nil {
		return nil, err
	}
	return decodeBSONDocument(raw)
}

// HexToPacket pins out a full LOCO packet (22-byte header + BSON body) from hex.
type PacketDump struct {
	ID       uint32 `json:"id"`
	Status   uint16 `json:"status"`
	Method   string `json:"method"`
	BodyType byte   `json:"body_type"`
	Body     any    `json:"body"`
	BodyRaw  string `json:"body_hex,omitempty"`
}

func (d *PacketDump) String() string {
	return fmt.Sprintf("%s id=%d status=%d", d.Method, d.ID, d.Status)
}

func HexToPacket(hexStr string) (*PacketDump, error) {
	raw, err := hex.DecodeString(hexStr)
	if err != nil {
		return nil, err
	}
	if len(raw) < packetHeaderSize {
		return nil, fmt.Errorf("packet too short for header: %d bytes", len(raw))
	}
	h, err := parsePacketHeader(raw)
	if err != nil {
		return nil, err
	}
	dump := &PacketDump{
		ID:       h.ID,
		Status:   h.Status,
		Method:   h.Method,
		BodyType: h.bodyType,
	}
	if len(raw) > packetHeaderSize {
		body := raw[packetHeaderSize:]
		dump.BodyRaw = hex.EncodeToString(body)
		decoded, err := decodeBSONDocument(body)
		if err != nil {
			dump.Body = map[string]any{"error": err.Error()}
		} else {
			dump.Body = decoded
		}
	}
	return dump, nil
}
