package main

import (
	_ "embed"
	"fmt"
	"io"
	"os"

	"go.yarn.social/lextwt"
	"go.yarn.social/types"

	twt_avro "go.sour.is/lextwt-encoding/twt-avro"
	twt_fbs "go.sour.is/lextwt-encoding/twt-fbs"
	twt_pb "go.sour.is/lextwt-encoding/twt-pb"
)

type TwtRegistry interface {
	Twters() []*types.Twter
	Preamble() lextwt.Comments
	Twts() types.Twts
	WriteTo(w io.Writer) (int64, error)
}

//go:embed example.txt
var input []byte

func main() {
	in := os.Stdin //bytes.NewReader(input)
	out := os.Stdout

	log := func(v ...any) { fmt.Fprint(os.Stderr, v...) }

	if len(os.Args) != 3 {
		log("usage: lextwt-registry <inputFormat> <outputFormat>")
	}

	inputType := os.Args[1]
	outputType := os.Args[2]

	var err error
	var registry TwtRegistry

	switch inputType {
	case "txt":
		registry, err = lextwt.ParseRegistry(in)
	case "fbs":
		var b []byte
		b, err = io.ReadAll(in)
		if err == nil {
			registry, err = twt_fbs.DecodeRegistry(b)
		}
	case "avro":
		var b []byte
		b, err = io.ReadAll(in)
		if err == nil {
			registry, err = twt_avro.DecodeRegistry(b)
		}
	case "pb":
		var b []byte
		b, err = io.ReadAll(in)
		if err == nil {
			registry, err = twt_pb.DecodeRegistry(b)
		}
	default:
		log(fmt.Errorf("unknown input format: %q", inputType))
		return
	}

	if err != nil {
		log(err)
		return
	}

	//	log(registry)

	switch outputType {
	case "txt":
		registry.WriteTo(out)
	case "fbs":
		b := twt_fbs.EncodeRegistry(registry)
		_, err = out.Write(b)
		if err != nil {
			log(err)
		}
	case "avro":
		b, err := twt_avro.EncodeRegistry(registry)
		if err != nil {
			log(err)
		}
		_, err = out.Write(b)
		if err != nil {
			log(err)
		}
	case "pb":
		b, err := twt_pb.EncodeRegistry(registry)
		if err != nil {
			log(err)
		}
		_, err = out.Write(b)
		if err != nil {
			log(err)
		}

	default:
		log(fmt.Errorf("unknown output format: %q", outputType))
		return
	}
}
