// verifychain: a thin command-line wrapper around the engine's own
// audit.VerifyChainReportAt. It has to live inside the engine module because
// the audit package is under internal/.
//
//	verifychain -log engine.log -jwks jwks.json [-state audit-chain.json]
//
// The log is the engine's stdout; audit events are the lines that are JSON
// objects (an optional "[engine] " prefix added by lelu-mcp is stripped).
package main

import (
	"bufio"
	"crypto/rsa"
	"encoding/base64"
	"encoding/json"
	"flag"
	"fmt"
	"math/big"
	"os"
	"strings"

	"github.com/lelu-ai/lelu/engine/internal/audit"
)

type jwks struct {
	Keys []struct {
		Kid string `json:"kid"`
		N   string `json:"n"`
		E   string `json:"e"`
	} `json:"keys"`
}

func main() {
	logPath := flag.String("log", "", "engine stdout log")
	jwksPath := flag.String("jwks", "", "saved copy of /.well-known/jwks.json")
	statePath := flag.String("state", "", "audit-chain.json (optional, enables truncation check)")
	flag.Parse()

	raw, err := os.ReadFile(*jwksPath)
	must(err)
	var set jwks
	must(json.Unmarshal(raw, &set))

	f, err := os.Open(*logPath)
	must(err)
	defer f.Close()
	var events []audit.Event
	sc := bufio.NewScanner(f)
	sc.Buffer(make([]byte, 1<<20), 1<<20)
	for sc.Scan() {
		line := strings.TrimPrefix(sc.Text(), "[engine] ")
		if !strings.HasPrefix(line, "{") {
			continue
		}
		var e audit.Event
		if json.Unmarshal([]byte(line), &e) != nil || e.Signature == "" {
			continue
		}
		events = append(events, e)
	}
	if len(events) == 0 {
		fmt.Println("no signed audit events found")
		os.Exit(2)
	}

	var pub *rsa.PublicKey
	for _, k := range set.Keys {
		if k.Kid == events[0].KeyID {
			n, err := base64.RawURLEncoding.DecodeString(k.N)
			must(err)
			e, err := base64.RawURLEncoding.DecodeString(k.E)
			must(err)
			pub = &rsa.PublicKey{N: new(big.Int).SetBytes(n), E: int(new(big.Int).SetBytes(e).Int64())}
		}
	}
	if pub == nil {
		fmt.Printf("no key with kid %q in the JWKS\n", events[0].KeyID)
		os.Exit(2)
	}

	var rep audit.ChainReport
	if *statePath != "" {
		_, highWater, err := audit.ReadChainState(*statePath)
		must(err)
		rep = audit.VerifyChainReportAt(events, pub, "", highWater)
	} else {
		rep = audit.VerifyChainReport(events, pub, "")
	}
	out, _ := json.MarshalIndent(struct {
		audit.ChainReport
		Complete bool `json:"complete"`
	}{rep, rep.Complete()}, "", "  ")
	fmt.Println(string(out))
	if !rep.Complete() {
		os.Exit(1)
	}
}

func must(err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(2)
	}
}
