// 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 balloon

import (
	"bytes"
	"errors"

	"go.cypherpunks.su/keks"
	cmenc "go.cypherpunks.su/keks/cm/enc"
	"go.cypherpunks.su/keks/cm/enc/chapoly"
	"go.cypherpunks.su/keks/schema"
)

// Possibly interactively decrypt passphrase-encrypted data.
func PossibleInteractiveDecrypt(in []byte) (out []byte, err error) {
	var magic keks.Magic
	magic, out = keks.StripMagic(in)
	if magic != cmenc.Magic {
		return in, nil
	}
	var encrypted cmenc.Encrypted
	var v any
	{
		d := keks.NewDecoderFromBytes(out, nil)
		v, err = d.Decode()
		if err != nil {
			return
		}
		err = schema.Check("encrypted", cmenc.EncryptedSchemas, v)
		if err != nil {
			return
		}
		err = d.UnmarshalStruct(&encrypted)
		if err != nil {
			return
		}
	}
	if encrypted.DEM.A != chapoly.DEMAlgo {
		err = errors.New("unsupported encryption DEM")
		return
	}
	if len(encrypted.KEM) != 1 ||
		encrypted.KEM[0].A != BalloonBLAKE2bHKDF ||
		len(encrypted.Payload) == 0 {
		err = errors.New("wrong encryption KEM")
		return
	}
	v = v.(map[string]any)["kem"].([]any)[0]
	err = schema.Check("kem-balloon-blake2b-hkdf", cmenc.EncryptedSchemas, v)
	if err != nil {
		return
	}
	var passwd []byte
	passwd, err = cmenc.ReadPasswd("Passphrase:")
	if err != nil {
		return
	}
	var cek []byte
	cek, err = Decapsulate(encrypted.KEM[0], encrypted.Id[:], passwd)
	if err != nil {
		return
	}
	var buf bytes.Buffer
	_, err = chapoly.Open(&buf, bytes.NewReader(encrypted.Payload), cek, 1)
	out = buf.Bytes()
	return
}
