package main

import (
	"encoding/json"
	"fmt"
	"io"
	"os"

	"git.virebent.art/virebent/yamnweb/yamn/encoder"
)

type request struct {
	Kind          encoder.Kind `json:"kind"`
	PublicKeyring string       `json:"public_keyring"`
	Entry         string       `json:"entry"`
	Chain         []string     `json:"chain"`
	From          string       `json:"from"`
	ReplyTo       string       `json:"reply_to"`
	To            string       `json:"to"`
	Subject       string       `json:"subject"`
	Newsgroup     string       `json:"newsgroup"`
	Body          string       `json:"body"`
	References    string       `json:"references"`
}

type response struct {
	Success      bool   `json:"success"`
	EntryAddress string `json:"entry_address,omitempty"`
	Envelope     string `json:"envelope,omitempty"`
	Error        string `json:"error,omitempty"`
}

func main() {
	var input request
	data, err := io.ReadAll(io.LimitReader(os.Stdin, 256*1024))
	if err == nil {
		err = json.Unmarshal(data, &input)
	}
	if err == nil {
		result, encodeErr := encoder.Encode(encoder.Request{
			Kind: input.Kind, PublicKeyring: input.PublicKeyring, Entry: input.Entry,
			Chain: input.Chain, From: input.From, ReplyTo: input.ReplyTo, To: input.To,
			Subject: input.Subject, Newsgroup: input.Newsgroup, Body: input.Body,
			References: input.References,
		})
		if encodeErr == nil {
			_ = json.NewEncoder(os.Stdout).Encode(response{Success: true, EntryAddress: result.EntryAddress, Envelope: string(result.Envelope)})
			return
		}
		err = encodeErr
	}
	_ = json.NewEncoder(os.Stdout).Encode(response{Success: false, Error: "YAMN encoding failed"})
	fmt.Fprintln(os.Stderr, "yamn-encode:", err)
	os.Exit(1)
}
