package mloco

import (
	"encoding/binary"
	"fmt"
	"math"
	"time"
)

const (
	bsonFloat64    byte = 0x01
	bsonString     byte = 0x02
	bsonDoc        byte = 0x03
	bsonArray      byte = 0x04
	bsonBinary     byte = 0x05
	bsonUndef      byte = 0x06
	bsonObjectID   byte = 0x07
	bsonBool       byte = 0x08
	bsonDate       byte = 0x09
	bsonNull       byte = 0x0A
	bsonRegex      byte = 0x0B
	bsonDBPtr      byte = 0x0C
	bsonCode       byte = 0x0D
	bsonSymbol     byte = 0x0E
	bsonCodeWS     byte = 0x0F
	bsonInt32      byte = 0x10
	bsonTimestamp  byte = 0x11
	bsonInt64      byte = 0x12
	bsonDecimal128 byte = 0x13
	bsonMinKey     byte = 0xFF
	bsonMaxKey     byte = 0x7F
)

type bsonValue struct {
	kind byte
	data any
}

func decodeBSONDocument(b []byte) (map[string]any, error) {
	if len(b) < 5 {
		return nil, fmt.Errorf("bson: document too short")
	}
	total := int(int32(binary.LittleEndian.Uint32(b)))
	if total < 5 || total > len(b) {
		return nil, fmt.Errorf("bson: invalid document length %d (buffer %d)", total, len(b))
	}
	doc, _, err := decodeBSONDocumentAt(b, 0, total)
	return doc, err
}

func decodeBSONDocumentAt(b []byte, offset int, end int) (map[string]any, int, error) {
	doc := map[string]any{}
	pos := offset + 4
	for pos < end {
		if b[pos] == 0x00 {
			pos++
			break
		}
		kind := b[pos]
		pos++
		nameEnd := pos
		for nameEnd < end && b[nameEnd] != 0x00 {
			nameEnd++
		}
		if nameEnd >= end {
			return nil, 0, fmt.Errorf("bson: unterminated key")
		}
		name := string(b[pos:nameEnd])
		pos = nameEnd + 1
		val, next, err := decodeBSONValue(b, pos, kind)
		if err != nil {
			return nil, 0, fmt.Errorf("bson: key %q: %w", name, err)
		}
		doc[name] = val
		pos = next
	}
	return doc, pos, nil
}

func decodeBSONValue(b []byte, pos int, kind byte) (any, int, error) {
	switch kind {
	case bsonFloat64:
		if pos+8 > len(b) {
			return nil, 0, fmt.Errorf("float64 out of bounds")
		}
		return math.Float64frombits(binary.LittleEndian.Uint64(b[pos:])), pos + 8, nil
	case bsonString:
		return decodeBSONString(b, pos)
	case bsonDoc:
		if pos+4 > len(b) {
			return nil, 0, fmt.Errorf("doc len out of bounds")
		}
		total := int(int32(binary.LittleEndian.Uint32(b[pos:])))
		if pos+total > len(b) {
			return nil, 0, fmt.Errorf("doc out of bounds")
		}
		doc, next, err := decodeBSONDocumentAt(b, pos, pos+total)
		return doc, next, err
	case bsonArray:
		if pos+4 > len(b) {
			return nil, 0, fmt.Errorf("array len out of bounds")
		}
		total := int(int32(binary.LittleEndian.Uint32(b[pos:])))
		if pos+total > len(b) {
			return nil, 0, fmt.Errorf("array out of bounds")
		}
		arr := []any{}
		p := pos + 4
		for p < pos+total {
			if b[p] == 0x00 {
				p++
				break
			}
			k := b[p]
			p++
			nameEnd := p
			for nameEnd < pos+total && b[nameEnd] != 0x00 {
				nameEnd++
			}
			p = nameEnd + 1
			val, nx, err := decodeBSONValue(b, p, k)
			if err != nil {
				return nil, 0, fmt.Errorf("bson array: %w", err)
			}
			arr = append(arr, val)
			p = nx
		}
		return arr, pos + total, nil
	case bsonBinary:
		if pos+5 > len(b) {
			return nil, 0, fmt.Errorf("binary len out of bounds")
		}
		l := int(int32(binary.LittleEndian.Uint32(b[pos:])))
		sub := b[pos+4]
		if pos+5+l > len(b) {
			return nil, 0, fmt.Errorf("binary data out of bounds")
		}
		return binaryData{subtype: sub, data: b[pos+5 : pos+5+l]}, pos + 5 + l, nil
	case bsonBool:
		if pos+1 > len(b) {
			return nil, 0, fmt.Errorf("bool out of bounds")
		}
		return b[pos] != 0, pos + 1, nil
	case bsonDate:
		if pos+8 > len(b) {
			return nil, 0, fmt.Errorf("date out of bounds")
		}
		ms := int64(binary.LittleEndian.Uint64(b[pos:]))
		return time.UnixMilli(ms).UTC(), pos + 8, nil
	case bsonNull:
		return nil, pos, nil
	case bsonInt32:
		if pos+4 > len(b) {
			return nil, 0, fmt.Errorf("int32 out of bounds")
		}
		return (any)(int32(binary.LittleEndian.Uint32(b[pos:]))), pos + 4, nil
	case bsonInt64:
		if pos+8 > len(b) {
			return nil, 0, fmt.Errorf("int64 out of bounds")
		}
		return int64(binary.LittleEndian.Uint64(b[pos:])), pos + 8, nil
	case bsonObjectID, bsonTimestamp, bsonCode, bsonSymbol, bsonUndef, bsonRegex, bsonDBPtr, bsonCodeWS, bsonDecimal128, bsonMinKey, bsonMaxKey:
		return opaqueValue{kind: kind, start: pos, b: b}, len(b), nil
	default:
		return nil, 0, fmt.Errorf("bson: unsupported kind 0x%02x at %d", kind, pos)
	}
}

func decodeBSONString(b []byte, pos int) (string, int, error) {
	if pos+4 > len(b) {
		return "", 0, fmt.Errorf("string len out of bounds")
	}
	l := int(int32(binary.LittleEndian.Uint32(b[pos:])))
	if l < 1 || pos+4+l > len(b) || b[pos+4+l-1] != 0x00 {
		return "", 0, fmt.Errorf("bson: invalid string length %d at %d", l, pos)
	}
	return string(b[pos+4 : pos+4+l-1]), pos + 4 + l, nil
}

type binaryData struct {
	subtype byte
	data    []byte
}

type opaqueValue struct {
	kind  byte
	start int
	b     []byte
}

type docMap map[string]any
type arrList []any

func encodeBSONDocument(doc map[string]any) []byte {
	body := []byte{}
	for k, v := range doc {
		body = append(body, encodeBSONElement(k, v)...)
	}
	body = append(body, 0x00)
	out := make([]byte, 4, 4+len(body))
	binary.LittleEndian.PutUint32(out, uint32(4+len(body)))
	out = append(out, body...)
	return out
}

func encodeBSONElement(name string, v any) []byte {
	out := []byte{}
	addName := func(kind byte) []byte {
		head := []byte{kind}
		head = append(head, []byte(name)...)
		return append(head, 0x00)
	}
	switch val := v.(type) {
	case (docMap):
		out = append(out, addName(bsonDoc)...)
		out = append(out, encodeBSONDocument(val)...)
	case (arrList):
		out = append(out, addName(bsonArray)...)
		out = append(out, encodeBSONArray(val)...)
	case string:
		out = append(out, addName(bsonString)...)
		out = append(out, encodeBSONCString(val)...)
	case int32:
		out = append(out, addName(bsonInt32)...)
		var buf [4]byte
		binary.LittleEndian.PutUint32(buf[:], uint32(val))
		out = append(out, buf[:]...)
	case int64:
		out = append(out, addName(bsonInt64)...)
		var buf [8]byte
		binary.LittleEndian.PutUint64(buf[:], uint64(val))
		out = append(out, buf[:]...)
	case int:
		out = append(out, addName(bsonInt32)...)
		var buf [4]byte
		binary.LittleEndian.PutUint32(buf[:], uint32(int32(val)))
		out = append(out, buf[:]...)
	case bool:
		out = append(out, addName(bsonBool)...)
		if val {
			out = append(out, 0x01)
		} else {
			out = append(out, 0x00)
		}
	case float64:
		out = append(out, addName(bsonFloat64)...)
		var buf [8]byte
		binary.LittleEndian.PutUint64(buf[:], math.Float64bits(val))
		out = append(out, buf[:]...)
	case nil:
		out = append(out, addName(bsonNull)...)
	case time.Time:
		out = append(out, addName(bsonDate)...)
		var buf [8]byte
		binary.LittleEndian.PutUint64(buf[:], uint64(val.UnixMilli()))
		out = append(out, buf[:]...)
	case binaryData:
		out = append(out, addName(bsonBinary)...)
		var buf [4]byte
		binary.LittleEndian.PutUint32(buf[:], uint32(len(val.data)))
		out = append(out, buf[:]...)
		out = append(out, val.subtype)
		out = append(out, val.data...)
	default:
		panic(fmt.Sprintf("mloco: cannot encode bson type %T", v))
	}
	return out
}

func encodeBSONArray(arr []any) []byte {
	body := []byte{}
	for i, v := range arr {
		body = append(body, encodeBSONElement(fmt.Sprintf("%d", i), v)...)
	}
	body = append(body, 0x00)
	out := make([]byte, 4, 4+len(body))
	binary.LittleEndian.PutUint32(out, uint32(4+len(body)))
	out = append(out, body...)
	return out
}

func encodeBSONCString(s string) []byte {
	b := make([]byte, 4+len(s)+1)
	binary.LittleEndian.PutUint32(b, uint32(len(s)+1))
	copy(b[4:], s)
	return b
}
