#!/usr/bin/env php
<?php
/*
 * run_conf10.php — replay the draft-zambo-aer1-10 corpus against
 * aer1verify.php, mirroring aer-1/conformance.py's traversal and verdict
 * logic vector for vector.
 *
 *   php run_conf10.php [/path/to/aer-1]   # exit 0 iff CONFORMANCE OK
 *
 * Written by ARION, an autonomous agent.
 */

$AER = $argv[1] ?? "/workspace/research/zambo-aer1/aer-1";
require __DIR__ . "/aer1verify.php";

$pass = 0; $fail = 0; $problems = [];
function verdict($corpus, $name, $ok, $detail = "") {
    global $pass, $fail, $problems;
    if ($ok) { $pass++; printf("[%-11s] %s: PASS\n", $corpus, $name); }
    else { $fail++; $problems[] = "$corpus $name"; printf("[%-11s] %s: FAIL %s\n", $corpus, $name, $detail); }
}
function reasons($r) { return array_map(fn($f) => $f["reason"], $r["failures"]); }
$OPT = ["kind"=>"auto","strict"=>false,"profile"=>false,"anchor"=>false];

// --- valid/: core check must return zero failures ----------------------
foreach (glob("$AER/test-vectors/valid/*.json") as $f) {
    $r = verifyDocument(json_decode(file_get_contents($f)), $OPT);
    verdict("valid", basename($f), count($r["failures"]) === 0,
            implode("; ", reasons($r)));
}
// --- invalid/: must be rejected ----------------------------------------
foreach (glob("$AER/test-vectors/invalid/*.json") as $f) {
    $r = verifyDocument(json_decode(file_get_contents($f)), $OPT);
    verdict("invalid", basename($f), count($r["failures"]) > 0,
            "accepted!");
}
// --- invalid-profile/: core MUST pass, profile MUST fail ----------------
foreach (glob("$AER/test-vectors/invalid-profile/*.json") as $f) {
    $doc = json_decode(file_get_contents($f));
    $core = verifyDocument($doc, $OPT);
    $prof = verifyDocument($doc, array_merge($OPT, ["profile"=>true]));
    $profFails = array_filter($prof["failures"],
        fn($x) => $x["check"] === "reference-profile");
    $ok = count($core["failures"]) === 0 && count($profFails) > 0;
    verdict("invalid-profile", basename($f), $ok,
            count($core["failures"]) ? "core: ".implode(";",reasons($core)) : "profile accepted");
}
// --- anchored/: anchored-valid passes tier; others fail tier -----------
foreach (glob("$AER/test-vectors/anchored/*.json") as $f) {
    $doc = json_decode(file_get_contents($f));
    $r = verifyDocument($doc, array_merge($OPT, ["anchor"=>true]));
    $coreFails = array_filter($r["failures"], fn($x) => $x["check"] === "core");
    $tierFails = array_filter($r["failures"],
        fn($x) => $x["check"] === "disinterested-tier");
    $expectPass = basename($f) === "anchored-valid.json";
    $ok = count($coreFails) === 0
        && ($expectPass ? count($tierFails) === 0 : count($tierFails) > 0);
    verdict("anchored", basename($f), $ok,
            implode("; ", reasons($r)));
}
// --- chain-vectors.json (v06 regression) --------------------------------
$corpus = json_decode(file_get_contents("$AER/chain-vectors.json"));
foreach ($corpus->vectors as $v) {
    $tl = $v->timeline ?? $v->entries ?? null;
    $r = verifyDocument($tl, array_merge($OPT, ["kind"=>"chain06"]));
    $ok = (count($r["failures"]) === 0) === ($v->expected_verdict === "valid");
    verdict("chain06", $v->name, $ok, implode("; ", reasons($r)));
}
// --- chain-vectors-v07.json ---------------------------------------------
$corpus = json_decode(file_get_contents("$AER/chain-vectors-v07.json"));
foreach ($corpus->vectors as $v) {
    $tl = $v->timeline ?? $v->entries ?? null;
    $r = verifyDocument($tl, array_merge($OPT, ["kind"=>"chain"]));
    $ok = (count($r["failures"]) === 0) === ($v->expected_verdict === "valid");
    verdict("chain-v07", $v->name, $ok, implode("; ", reasons($r)));
}
// --- commitment-vectors.json --------------------------------------------
$corpus = json_decode(file_get_contents("$AER/commitment-vectors.json"));
foreach ($corpus->vectors as $v) {
    $fails = verifyChainCommitment($v->timeline ?? null, $v->commitment ?? null, $OPT);
    $ok = (count($fails) === 0) === ($v->expected_verdict === "valid");
    verdict("commitment", $v->name, $ok, implode("; ", $fails));
}
// --- merkle-vectors.json -------------------------------------------------
$corpus = json_decode(file_get_contents("$AER/merkle-vectors.json"));
foreach ($corpus->vectors as $v) {
    if (isset($v->receipt_ids)) {
        $got = merkleRoot($v->receipt_ids);
        verdict("merkle", $v->name, $got === $v->expected_root, "got $got");
    } elseif (isset($v->leaves)) {
        $leaves = $v->leaves;
        usort($leaves, fn($a,$b) => $a->seq <=> $b->seq);
        $lvl = array_map(fn($l) => hash("sha256", $l->preimage, true), $leaves);
        while (count($lvl) > 1) {
            if (count($lvl) % 2) $lvl[] = end($lvl);
            $next = [];
            for ($i = 0; $i < count($lvl); $i += 2)
                $next[] = hash("sha256", $lvl[$i].$lvl[$i+1], true);
            $lvl = $next;
        }
        $got = $lvl ? bin2hex($lvl[0]) : hash("sha256", "");
        $ok = $got === $v->expected_root
            && (!isset($v->must_not_equal) || $got !== $v->must_not_equal);
        verdict("merkle-legacy", $v->name, $ok, "got $got");
    }
    if (isset($v->expected_workflow_verdict)) {
        if (!isset($v->receipt_ids)) { verdict("merkle-wf", $v->name, false, "no receipt_ids"); continue; }
        $wf = (object)[
            "type" => "verifiable-workflow-receipt", "version" => "1",
            "workflow_id" => "11111111-1111-1111-1111-111111111111",
            "receipt_id" => "22222222-2222-2222-2222-222222222222",
            "session_id" => "test-session", "goal" => "test workflow",
            "status" => "ok",
            "steps" => array_map(fn($i) => (object)[
                "seq" => $i + 1, "tool" => "test-tool",
                "receipt_id" => $v->receipt_ids[$i],
                "receipt_hash" => str_repeat("a", 64),
                "started_at" => "2026-01-01T00:00:00Z",
                "ended_at" => "2026-01-01T00:00:01Z", "status" => "ok",
            ], array_keys($v->receipt_ids)),
            "merkle_root" => $v->expected_root,
            "output_hash" => str_repeat("b", 64),
            "verify_url" => "https://example.com/workflow/test",
        ];
        $wfFails = checkWorkflow($wf, $OPT);
        $verdict = count($wfFails) === 0 ? "valid" : "invalid";
        $ok = $verdict === $v->expected_workflow_verdict;
        if ($ok && $verdict === "invalid" && isset($v->rejected_by)) {
            $ok = false;
            foreach ($wfFails as $f) if (strpos($f, $v->rejected_by) !== false) $ok = true;
        }
        verdict("merkle-wf", $v->name, $ok, "verdict $verdict");
    }
}

printf("\n== SUMMARY ==  %d passed, %d failed\n", $pass, $fail);
if ($fail) { foreach ($problems as $p) echo " - $p\n"; exit(1); }
echo "CONFORMANCE OK (-10 corpus): all vectors behave as expected.\n";
exit(0);
