// CAIN-42 E82 — independent Go verifier.
// Standard library only. No CAIN code. Third-language implementation, not a third-party audit.
package main

import (
	"bufio"
	"crypto/ed25519"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

type Entry struct {
	Path   string `json:"path"`
	SHA256 string `json:"sha256"`
}
type Manifest struct {
	Files              []Entry `json:"files"`
	FileCount          int     `json:"file_count"`
	MerkleRoot         string  `json:"merkle_root"`
	SignerPublicKeyB64 string  `json:"signer_public_key_b64"`
	KeyClass           string  `json:"key_class"`
	IndependentWitness bool    `json:"independent_witness"`
}

type Check struct {
	Check  string      `json:"check"`
	OK     bool        `json:"ok"`
	Detail interface{} `json:"detail,omitempty"`
}
type Report struct {
	Schema        string  `json:"schema"`
	OK            bool    `json:"ok"`
	ChecksPassed  int     `json:"checks_passed"`
	ChecksTotal   int     `json:"checks_total"`
	MerkleRoot    string  `json:"merkle_root"`
	FileCount     int     `json:"file_count"`
	GoVersion     string  `json:"go_version"`
	Checks        []Check `json:"checks"`
	EvidenceClass string  `json:"evidence_class"`
	Note          string  `json:"note"`
}

var checks []Check

func add(name string, ok bool, detail interface{}) {
	checks = append(checks, Check{name, ok, detail})
}
func die(err error) {
	fmt.Fprintln(os.Stderr, err)
	os.Exit(1)
}
func shaHex(b []byte) string {
	s := sha256.Sum256(b)
	return hex.EncodeToString(s[:])
}
func shaFile(p string) (string, error) {
	b, err := os.ReadFile(p)
	if err != nil {
		return "", err
	}
	return shaHex(b), nil
}
func walk(root, dir string) ([]string, error) {
	var out []string
	ents, err := os.ReadDir(filepath.Join(root, dir))
	if err != nil {
		return nil, err
	}
	for _, e := range ents {
		rel := filepath.Join(dir, e.Name())
		if e.IsDir() {
			sub, err := walk(root, rel)
			if err != nil {
				return nil, err
			}
			out = append(out, sub...)
		} else {
			out = append(out, rel)
		}
	}
	return out, nil
}
func merkle(leaves []string) string {
	if len(leaves) == 0 {
		return strings.Repeat("0", 64)
	}
	level := make([][]byte, 0, len(leaves))
	for _, h := range leaves {
		b, _ := hex.DecodeString(h)
		level = append(level, b)
	}
	for len(level) > 1 {
		var next [][]byte
		for i := 0; i < len(level); i += 2 {
			if i+1 < len(level) {
				buf := append([]byte{1}, level[i]...)
				buf = append(buf, level[i+1]...)
				h := sha256.Sum256(buf)
				next = append(next, h[:])
			} else {
				next = append(next, level[i])
			}
		}
		level = next
	}
	return hex.EncodeToString(level[0])
}
func readJSON(path string) (map[string]interface{}, error) {
	var m map[string]interface{}
	b, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	err = json.Unmarshal(b, &m)
	return m, err
}
func readJSONL(path string) ([]map[string]interface{}, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	var out []map[string]interface{}
	sc := bufio.NewScanner(f)
	sc.Buffer(make([]byte, 1024*1024), 16*1024*1024)
	for sc.Scan() {
		if strings.TrimSpace(sc.Text()) == "" {
			continue
		}
		var m map[string]interface{}
		if err := json.Unmarshal(sc.Bytes(), &m); err != nil {
			return nil, err
		}
		out = append(out, m)
	}
	return out, sc.Err()
}
func num(v interface{}) float64 {
	if f, ok := v.(float64); ok {
		return f
	}
	return -1
}
func str(v interface{}) string {
	if s, ok := v.(string); ok {
		return s
	}
	return ""
}

func main() {
	root := "bundle"
	if len(os.Args) > 1 {
		root = os.Args[1]
	}
	mb, err := os.ReadFile(filepath.Join(root, "MANIFEST.json"))
	if err != nil {
		die(err)
	}
	var m Manifest
	if err := json.Unmarshal(mb, &m); err != nil {
		die(err)
	}
	sig, err := os.ReadFile(filepath.Join(root, "MANIFEST.sig"))
	if err != nil {
		die(err)
	}
	sigRaw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(sig)))
	if err != nil {
		die(err)
	}
	pubRaw, err := base64.StdEncoding.DecodeString(m.SignerPublicKeyB64)
	if err != nil || len(pubRaw) != ed25519.PublicKeySize {
		add("manifest_signature", false, "bad public key")
	} else {
		add("manifest_signature", ed25519.Verify(ed25519.PublicKey(pubRaw), mb, sigRaw),
			"Ed25519 over MANIFEST.json bytes")
	}

	listed := map[string]string{}
	var leaves []string
	for _, e := range m.Files {
		listed[e.Path] = e.SHA256
		leaves = append(leaves, e.SHA256)
	}
	var missing, bad []string
	for rel, want := range listed {
		got, err := shaFile(filepath.Join(root, rel))
		if err != nil {
			missing = append(missing, rel)
		} else if got != want {
			bad = append(bad, rel)
		}
	}
	add("files_present", len(missing) == 0, missing)
	add("file_hashes", len(bad) == 0, bad)
	onDisk, err := walk(root, ".")
	if err != nil {
		die(err)
	}
	var extra []string
	for _, rel := range onDisk {
		if rel == "MANIFEST.json" || rel == "MANIFEST.sig" {
			continue
		}
		if _, ok := listed[rel]; !ok {
			extra = append(extra, rel)
		}
	}
	add("no_unlisted_files", len(extra) == 0, extra)
	add("file_count", m.FileCount == len(listed), []int{m.FileCount, len(listed)})
	rootHash := merkle(leaves)
	add("merkle_root", rootHash == m.MerkleRoot, rootHash)
	add("key_class", m.KeyClass == "SELF_GENERATED_OPERATOR_KEY", m.KeyClass)
	add("independent_witness_false", m.IndependentWitness == false, m.IndependentWitness)

	// Benchmark recompute.
	if b, err := readJSON(filepath.Join(root, "benchmark/benchmark.json")); err == nil {
		rows, _ := readJSONL(filepath.Join(root, "benchmark/benchmark_rows.jsonl"))
		byModel, _ := b["by_model"].(map[string]interface{})
		for model, raw := range byModel {
			rec, _ := raw.(map[string]interface{})
			var n, k int
			for _, r := range rows {
				if str(r["model_key"]) == model && r["scored"] != false {
					n++
					if ok, _ := r["correct"].(bool); ok {
						k++
					}
				}
			}
			acc := -1.0
			if n > 0 {
				acc = float64(k) / float64(n)
			}
			add("benchmark:"+model, n == int(num(rec["n"])) && k == int(num(rec["correct"])) &&
				fmt.Sprintf("%.6f", acc) == fmt.Sprintf("%.6f", num(rec["accuracy"])),
				fmt.Sprintf("%d/%d", k, n))
		}
		add("benchmark_no_remote", num(b["real_remote_calls"]) == 0, b["real_remote_calls"])
	} else {
		add("benchmark", false, err.Error())
	}

	// Collaboration recompute.
	if c, err := readJSON(filepath.Join(root, "collaboration/collaboration.json")); err == nil {
		rows, _ := readJSONL(filepath.Join(root, "collaboration/collaboration_rows.jsonl"))
		arms, _ := c["arm_stats"].(map[string]interface{})
		for arm, raw := range arms {
			rec, _ := raw.(map[string]interface{})
			var n, k int
			for _, r := range rows {
				if str(r["arm"]) == arm {
					n++
					if ok, _ := r["correct"].(bool); ok {
						k++
					}
				}
			}
			acc := -1.0
			if n > 0 {
				acc = float64(k) / float64(n)
			}
			add("collab:"+arm, n == int(num(rec["n"])) && k == int(num(rec["correct"])) &&
				fmt.Sprintf("%.6f", acc) == fmt.Sprintf("%.6f", num(rec["accuracy"])),
				fmt.Sprintf("%d/%d", k, n))
		}
	} else {
		add("collaboration", false, err.Error())
	}

	// Gates.
	if g, err := readJSON(filepath.Join(root, "acceptance_matrix.json")); err == nil {
		gates, _ := g["gates"].([]interface{})
		add("gates_count", len(gates) >= 40, len(gates))
		counts := map[string]int{}
		valid := true
		for _, raw := range gates {
			x, _ := raw.(map[string]interface{})
			s := str(x["status"])
			counts[s]++
			if s != "PASS" && s != "PARTIAL" && s != "FAIL" && s != "BLOCKED" && s != "NOT EVALUABLE" {
				valid = false
			}
		}
		add("gates_statuses", valid, counts)
	} else {
		add("gates", false, err.Error())
	}

	// Findings + recovery + endurance.
	if f, err := readJSON(filepath.Join(root, "findings_closure.json")); err == nil {
		f01, _ := f["F-01"].(map[string]interface{})
		add("f01_unique_invocations", num(f01["unique_invocations"]) == 1589, f01["unique_invocations"])
		add("f01_no_remote", num(f01["real_remote_responses"]) == 0, f01["real_remote_responses"])
	} else {
		add("findings", false, err.Error())
	}
	if x, err := readJSON(filepath.Join(root, "crosshost/crosshost.json")); err == nil {
		add("crosshost_completed", str(x["mission_state_on_b"]) == "COMPLETED", x["mission_state_on_b"])
		add("crosshost_no_duplicates", num(x["duplicate_effects"]) == 0, x["duplicate_effects"])
	} else {
		add("crosshost", false, err.Error())
	}
	if e, err := readJSON(filepath.Join(root, "endurance/endurance.json")); err == nil {
		add("endurance_real_clock", str(e["clock"]) == "REAL_WALL_CLOCK" && e["target_reached"] == true, e["elapsed_s"])
		add("endurance_no_duplicates", num(e["duplicate_effects"]) == 0, e["duplicate_effects"])
	} else {
		add("endurance", false, err.Error())
	}

	ok := true
	passed := 0
	for _, c := range checks {
		if c.OK {
			passed++
		} else {
			ok = false
		}
	}
	rep := Report{
		Schema:        "cain2027.e82.go_verification.v1",
		OK:            ok,
		ChecksPassed:  passed,
		ChecksTotal:   len(checks),
		MerkleRoot:    rootHash,
		FileCount:     len(listed),
		GoVersion:     "go1.27.1",
		Checks:        checks,
		EvidenceClass: "THIRD_LANGUAGE_IMPLEMENTATION",
		Note:          "Go standard library only; no CAIN imports. This is an independent implementation, not a third-party audit.",
	}
	out, _ := json.MarshalIndent(rep, "", " ")
	fmt.Println(string(out))
	if !ok {
		os.Exit(1)
	}
}
