// KEKS -- Go KEKS codec implementation
// Copyright (C) 2024-2025 Sergey Matveev <stargrave@stargrave.org>
//
// This program 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, version 3 of the License.
//
// This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

package keks

import "go.cypherpunks.su/keks/types"

// Magic string. Up to 12 bytes.
type Magic string

var MagicDecodeOpts = DecodeOpts{
	MaxStrLen:        16,
	MaxContLen:       0,
	DisableUTF8Check: true,
	LeaveTAI64:       true,
}

// Strip off possible Magic atom at the beginning. If not Magic is
// present, then return empty Magic and data unchanged.
func StripMagic(data []byte) (Magic, []byte) {
	d := NewDecoderFromBytes(data, &MagicDecodeOpts)
	t, err := d.DecodeAtom()
	if err != nil {
		return "", data
	}
	if t != types.Magic {
		return "", data
	}
	return d.Iter().Magic(), data[d.Read:]
}

func (m Magic) MarshalJSON() ([]byte, error) {
	return []byte(`"MAGIC[` + m + `]"`), nil
}
