// schema-validate -- KEKS data structures validator
// 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 main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"io"
	"log"
	"os"

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

func main() {
	flag.Parse()
	log.SetFlags(0)
	if flag.NArg() != 2 {
		fmt.Fprintf(os.Stderr, "Usage: schema-validate SCHEMA.keks SCHEMA-NAME <DATA.keks\n")
		os.Exit(1)
	}
	schemasRaw, err := os.ReadFile(flag.Arg(0))
	if err != nil {
		log.Fatal(err)
	}
	dataRaw, err := io.ReadAll(bufio.NewReader(os.Stdin))
	if err != nil {
		log.Fatal(err)
	}

	magic, schemasRaw := keks.StripMagic(schemasRaw)
	if magic != schema.Magic {
		log.Fatal("bad schema magic")
	}

	_, dataRaw = keks.StripMagic(dataRaw)
	d := keks.NewDecoderFromBytes(schemasRaw, nil)
	var schemas map[string][][]any
	err = d.DecodeStruct(&schemas)
	if err != nil {
		log.Fatal(err)
	}

	d = keks.NewDecoderFromBytes(dataRaw, &keks.DecodeOpts{LeaveTAI64: true})
	data, err := d.Decode()
	if err != nil {
		log.Fatal(err)
	}

	err = schema.Check(flag.Arg(1), schemas, data)
	var bad bool
CheckErr:
	if err != nil {
		bad = true
		log.Print(err)
		err = errors.Unwrap(err)
		goto CheckErr
	}
	if bad {
		os.Exit(1)
	}
}
