// KEKS/CM -- KEKS-encoded cryptographic messages
// 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 sign

import (
	"errors"
	"fmt"

	"go.cypherpunks.su/keks"
	"go.cypherpunks.su/keks/cm"
	ed25519blake2b "go.cypherpunks.su/keks/cm/sign/ed25519-blake2b"
	"go.cypherpunks.su/keks/cm/sign/gost"
	"go.cypherpunks.su/keks/cm/sign/slhdsa"
	"go.cypherpunks.su/keks/schema"
)

const PrvMagic = keks.Magic("cm/prv")

// Parse private key contained in AV KEKS-encoded structure.
func PrvParse(data []byte) (prv Iface, pub []byte, err error) {
	{
		var magic keks.Magic
		magic, data = keks.StripMagic(data)
		if magic != "" && magic != PrvMagic {
			err = errors.New("wrong magic")
			return
		}
	}
	d := keks.NewDecoderFromBytes(data, &keks.DecodeOpts{MaxStrLen: 1 << 16})
	{
		var v any
		v, err = d.Decode()
		if err != nil {
			return
		}
		err = schema.Check("av", PubSchemas, v)
		if err != nil {
			return
		}
	}
	var av cm.AV
	if err = d.UnmarshalStruct(&av); err != nil {
		return
	}
	switch av.A {
	case ed25519blake2b.Ed25519BLAKE2b:
		prv, pub, err = ed25519blake2b.NewSigner(av.V)
	case gost.GOST3410256A, gost.GOST3410512C:
		prv, pub, err = gost.NewSigner(av.V)
	case slhdsa.SLHDSASHAKE256s:
		prv, pub, err = slhdsa.NewSigner(av.V)
	default:
		err = fmt.Errorf("unknown private key algo: %s", av.A)
	}
	return
}
