// Command h2inspect reads a raw HTTP/2 byte stream from stdin (or a
// file), prints a frame-by-frame trace, and decodes HEADERS via HPACK —
// the same view as `nghttp -v`, reconstructed from the wire so you
// understand the bytes, not just the tool's output.
//
//	go build -o /tmp/h2inspect ./cmd/h2inspect
//	# capture a cleartext h2c stream, then:
//	/tmp/h2inspect < capture.bin
//
// Note: real captures Huffman-code headers; this lab decoder surfaces
// that as "[huffman]" rather than guessing. The frame layer, stream
// demux, and flow control all work regardless.
package main

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

	"gw02/h2"
)

func main() {
	file := flag.String("f", "", "input file (default: stdin)")
	flag.Parse()

	var r io.Reader = os.Stdin
	if *file != "" {
		f, err := os.Open(*file)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		defer f.Close()
		r = f
	}
	br := bufio.NewReader(r)

	// Skip the client preface if present.
	if pre, _ := br.Peek(len(h2.ClientPreface)); string(pre) == h2.ClientPreface {
		io.CopyN(io.Discard, br, int64(len(h2.ClientPreface)))
		fmt.Println("[client preface]")
	}

	dm := h2.NewDemux()
	for {
		f, err := h2.ReadFrame(br)
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Fprintln(os.Stderr, "read:", err)
			break
		}
		fmt.Println(f)
		hdrs, derr := dm.Process(f)
		for _, h := range hdrs {
			fmt.Printf("    %s\n", h)
		}
		if errors.Is(derr, h2.ErrHuffman) {
			fmt.Println("    [huffman-coded headers — see x/net/http2/hpack]")
		} else if derr != nil {
			fmt.Fprintln(os.Stderr, "  decode:", derr)
		}
	}
	fmt.Printf("active streams (multiplexed on one connection): %v\n", dm.ActiveStreams())
}
