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

import (
	"bytes"
	"crypto/rand"
	"fmt"
	"io"
	"net/rpc"
	"sync"

	"github.com/google/uuid"

	"go.cypherpunks.su/keks"
	"go.cypherpunks.su/keks/schema"
)

type SeqAndMethod struct {
	method string
	seq    uint64
}

type ClientCodec struct {
	conn     io.ReadWriteCloser
	body     map[string]any
	pending  map[uuid.UUID]SeqAndMethod
	rnd      [16]byte
	pendingM sync.Mutex
}

func NewClientCodec(conn io.ReadWriteCloser) *ClientCodec {
	cc := ClientCodec{
		conn:    conn,
		pending: make(map[uuid.UUID]SeqAndMethod),
	}
	rand.Read(cc.rnd[:])
	return &cc
}

func (cc *ClientCodec) WriteRequest(req *rpc.Request, data any) (err error) {
	var id uuid.UUID
	id, err = uuid.NewV7FromReader(bytes.NewReader(cc.rnd[:]))
	if err != nil {
		panic(err)
	}
	cc.pendingM.Lock()
	cc.pending[id] = SeqAndMethod{seq: req.Seq, method: req.ServiceMethod}
	cc.pendingM.Unlock()
	if _, err = keks.Encode(cc.conn, []any{"c", id, req.ServiceMethod, data}, nil); err != nil {
		return fmt.Errorf("keks/rpc: WriteRequest: %w", err)
	}
	return nil
}

func (cc *ClientCodec) ReadResponseHeader(resp *rpc.Response) (err error) {
	d := keks.NewDecoderFromReader(cc.conn, nil)
	var r any
	if r, err = d.Decode(); err != nil {
		return fmt.Errorf("keks/rpc: ReadResponseHeader: %w", err)
	}
	if err = schema.Check("reply", RPCSchemas, r); err != nil {
		return fmt.Errorf("keks/rpc: ReadResponseHeader: %w", err)
	}
	list := r.([]any)
	id := list[1].(*keks.Hexlet).UUID()
	cc.pendingM.Lock()
	seqAndMethod, ok := cc.pending[id]
	if ok {
		delete(cc.pending, id)
	}
	cc.pendingM.Unlock()
	if !ok {
		return fmt.Errorf("keks/rpc: ReadResponseHeader: unknown id: %s", id)
	}
	resp.Seq, resp.ServiceMethod = seqAndMethod.seq, seqAndMethod.method
	resp.Error = list[2].(string)
	cc.body = list[3].(map[string]any)
	return nil
}

func (cc *ClientCodec) ReadResponseBody(dst any) (err error) {
	if dst == nil {
		return nil
	}
	if err = keks.Map2Struct(dst, cc.body); err != nil {
		return fmt.Errorf("keks/rpc: ReadResponseBody: %w", err)
	}
	return nil
}

func (cc *ClientCodec) Close() error {
	return cc.conn.Close()
}

func NewClient(conn io.ReadWriteCloser) *rpc.Client {
	return rpc.NewClientWithCodec(NewClientCodec(conn))
}
