// 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 (
	"fmt"
	"io"
	"net/rpc"
	"sync"

	"github.com/google/uuid"
	"go.cypherpunks.su/keks"
	"go.cypherpunks.su/keks/schema"
)

type ServerCodec struct {
	conn io.ReadWriteCloser
	ids  map[uint64]uuid.UUID
	body map[string]any
	seq  uint64
	idsM sync.Mutex
}

func NewServerCodec(conn io.ReadWriteCloser) *ServerCodec {
	return &ServerCodec{conn: conn, ids: make(map[uint64]uuid.UUID)}
}

func (sc *ServerCodec) ReadRequestHeader(req *rpc.Request) (err error) {
	d := keks.NewDecoderFromReader(sc.conn, nil)
	var r any
	if r, err = d.Decode(); err != nil {
		return fmt.Errorf("keks/rpc: ReadRequestHeader: %w", err)
	}
	if err = schema.Check("call", RPCSchemas, r); err != nil {
		return fmt.Errorf("keks/rpc: ReadRequestHeader: %w", err)
	}
	list := r.([]any)
	sc.idsM.Lock()
	sc.seq++
	req.Seq = sc.seq
	sc.ids[sc.seq] = list[1].(*keks.Hexlet).UUID()
	sc.idsM.Unlock()
	req.ServiceMethod = list[2].(string)
	sc.body = list[3].(map[string]any)
	return nil
}

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

func (sc *ServerCodec) WriteResponse(resp *rpc.Response, data any) (err error) {
	sc.idsM.Lock()
	id, ok := sc.ids[resp.Seq]
	if !ok {
		panic("unknown id")
	}
	delete(sc.ids, resp.Seq)
	sc.idsM.Unlock()
	if _, err = keks.Encode(sc.conn, []any{"r", id, resp.Error, data}, nil); err != nil {
		return fmt.Errorf("keks/rpc: WriteResponse: %w", err)
	}
	return nil
}

func (sc *ServerCodec) Close() error {
	return sc.conn.Close()
}

func ServeConn(conn io.ReadWriteCloser) {
	rpc.ServeCodec(NewServerCodec(conn))
}
