import io, sys

P = "crates/spt-live/src/echo.rs"
with io.open(P, "r", encoding="utf-8", newline="") as f:
    src = f.read()

NL = "\r\n" if "\r\n" in src else "\n"


def sub(old, new, label):
    global src
    n = src.count(old)
    if n != 1:
        sys.exit("ANCHOR %s matched %d times (need exactly 1)" % (label, n))
    src = src.replace(old, new, 1)


def L(*lines):
    return NL.join(lines)


Q = '\\"'  # an escaped quote inside a Rust string literal

# ------------------------------------------------- test 1: consumes + stamps
sub(
    L(
        "    #[test] // [unit->REQ-SEAM-HISTORY] echo consumes history + emits a single-writer commune drop.",
        "    fn echo_consumes_history_and_writes_commune() {",
        "        let dir = tempfile::tempdir().unwrap();",
        "        let rt = ManifestRuntime::new(echo_manifest(PASSTHROUGH, false));",
        '        let history = recs(&["{%sr%s:%su%s,%st%s:%shi%s}", "{%sr%s:%sa%s,%st%s:%syo%s}"]);'
        % ((Q,) * 16),
        "        let res = run_echo_commune(",
        "            &rt,",
        '            "doyle",',
        "            &BTreeMap::new(),",
        "            &history,",
        "            dir.path(),",
        "            Duration::from_secs(10),",
        "        )",
        '        .expect("echo");',
        "",
        '        assert_eq!(res.drop_path, dir.path().join("doyle-commune.md"));',
        "        let written = std::fs::read_to_string(&res.drop_path).unwrap();",
        "        // [unit->REQ-HAZARD-DROP-FILE-SINGLE-WRITER] spt-core wrote the drop file.",
        "        assert!(",
        '            written.starts_with("Source: echo-commune\\n"),',
        '            "provenance: {written:?}"',
        "        );",
        "        assert!(",
        '            written.contains("%st%s:%shi%s"),' % ((Q,) * 4),
        '            "consumed history: {written:?}"',
        "        );",
        '        assert!(written.contains("%st%s:%syo%s"));' % ((Q,) * 4),
        "    }",
    ),
    L(
        "    // [unit->REQ-SEAM-HISTORY] the echo consumes the history it is fed.",
        "    // [unit->REQ-ECHO-BRIEF-DIRECT-ROUTE] and RETURNS the brief already stamped,",
        "    // for the caller to route. The proof that nothing is filed is structural and",
        "    // stronger than an assertion could be: the signature takes no directory, so",
        "    // there is no path for this seam to write to.",
        "    #[test]",
        "    fn echo_consumes_history_and_returns_stamped_brief() {",
        "        let rt = ManifestRuntime::new(echo_manifest(PASSTHROUGH, false));",
        '        let history = recs(&["{%sr%s:%su%s,%st%s:%shi%s}", "{%sr%s:%sa%s,%st%s:%syo%s}"]);'
        % ((Q,) * 16),
        "        let res = run_echo_commune(",
        "            &rt,",
        '            "doyle",',
        "            &BTreeMap::new(),",
        "            &history,",
        "            Duration::from_secs(10),",
        "        )",
        '        .expect("echo");',
        "",
        "        assert!(",
        '            res.body.starts_with("Source: echo-commune\\n"),',
        '            "provenance: {:?}",',
        "            res.body",
        "        );",
        "        assert!(",
        '            res.body.contains("%st%s:%shi%s"),' % ((Q,) * 4),
        '            "consumed history: {:?}",',
        "            res.body",
        "        );",
        '        assert!(res.body.contains("%st%s:%syo%s"));' % ((Q,) * 4),
        "    }",
    ),
    "test-consumes",
)

# ------------------------------------------------------- test 2: guard child
sub(
    L(
        "    fn echo_child_is_recursion_guarded() {",
        "        let dir = tempfile::tempdir().unwrap();",
        "        let rt = ManifestRuntime::new(echo_manifest(GUARD_ECHO, true));",
        "        let res = run_echo_commune(",
        "            &rt,",
        '            "doyle",',
        "            &BTreeMap::new(),",
        "            &[],",
        "            dir.path(),",
        "            Duration::from_secs(10),",
        "        )",
        '        .expect("echo");',
    ),
    L(
        "    fn echo_child_is_recursion_guarded() {",
        "        let rt = ManifestRuntime::new(echo_manifest(GUARD_ECHO, true));",
        "        let res = run_echo_commune(",
        "            &rt,",
        '            "doyle",',
        "            &BTreeMap::new(),",
        "            &[],",
        "            Duration::from_secs(10),",
        "        )",
        '        .expect("echo");',
    ),
    "test-guard",
)

# ---------------------------------------------------------- test 3: non-zero
sub(
    L(
        "    #[test] // [unit->REQ-SEAM-HISTORY] a failing summarizer surfaces NonZero, no half-written drop.",
        "    fn echo_nonzero_errors() {",
        "        let dir = tempfile::tempdir().unwrap();",
        "        let rt = ManifestRuntime::new(echo_manifest(FAIL, false));",
        "        let e = run_echo_commune(",
        "            &rt,",
        '            "doyle",',
        "            &BTreeMap::new(),",
        "            &[],",
        "            dir.path(),",
        "            Duration::from_secs(10),",
        "        )",
        "        .unwrap_err();",
        '        assert!(matches!(e, EchoError::NonZero { .. }), "got {e}");',
        "        assert!(",
        '            !dir.path().join("doyle-commune.md").exists(),',
        '            "no drop on failure"',
        "        );",
        "    }",
    ),
    L(
        "    // [unit->REQ-SEAM-HISTORY] a failing summarizer surfaces NonZero and no brief.",
        "    //",
        "    // The old cell also asserted that no drop file appeared. That assertion is",
        "    // deleted rather than kept: with the write gone it can no longer fail, and an",
        "    // assertion that cannot go red reads as coverage while proving nothing. The",
        "    // real no-write proof is the lifecycle byte-identity cell, which DOES go red",
        "    // when the write is restored.",
        "    #[test]",
        "    fn echo_nonzero_errors() {",
        "        let rt = ManifestRuntime::new(echo_manifest(FAIL, false));",
        "        let e = run_echo_commune(",
        "            &rt,",
        '            "doyle",',
        "            &BTreeMap::new(),",
        "            &[],",
        "            Duration::from_secs(10),",
        "        )",
        "        .unwrap_err();",
        '        assert!(matches!(e, EchoError::NonZero { .. }), "got {e}");',
        "    }",
    ),
    "test-nonzero",
)

# ------------------------------------------------------- test 4: provenance tag
sub(
    "    #[test] // [unit->REQ-HAZARD-DROP-FILE-SINGLE-WRITER] provenance header is stamped by spt-core.",
    "    #[test] // [unit->REQ-ECHO-BRIEF-DIRECT-ROUTE] provenance header is stamped by spt-core.",
    "test-provenance-tag",
)

# ------------------------------- delete the retired write-retry cell entirely
start = src.index("    // [unit->REQ-ECHO-DROP-DIR-RESOLVE] the drop-write retry is bounded and")
end = src.rindex("}")  # closing brace of `mod tests`
tail = src[start:end]
if "drop_write_retry_is_bounded_and_denied_only" not in tail:
    sys.exit("retry cell not found in the deleted region")
src = src[:start].rstrip() + NL + "}" + NL

with io.open(P, "w", encoding="utf-8", newline="") as f:
    f.write(src)

print("echo.rs tests: repinned; retry cell deleted")
