#!/usr/bin/env python3
"""Tests for Story 2.05 (Track B): build_envelope XML Assembly"""
import xml.etree.ElementTree as ET
import sys
sys.path.insert(0, '/mnt/e/genesis-system')


def test_build_envelope():
    from core.memory.zero_amnesia_envelope import build_envelope, MemoryContext

    # BB1: All fields None → fallback strings
    ctx = MemoryContext(None, None, None, 12.5)
    xml_str = build_envelope(ctx)
    assert "Cold start. No prior state." in xml_str
    assert "No KG context available." in xml_str
    assert "No prior scars for this task type." in xml_str

    # BB2: Output passes XML validation
    root = ET.fromstring(xml_str)
    assert root.tag == "ZERO_AMNESIA_STATE"
    assert root.find("WORKING_CONTEXT") is not None
    assert root.find("TOPOLOGICAL_BLAST_RADIUS") is not None
    assert root.find("LEARNED_CONSTRAINTS") is not None
    assert root.find("HYDRATION_LATENCY_MS") is not None

    # BB3: Content with < character → escaped
    ctx = MemoryContext("x < y & z > w", None, None, 5.0)
    xml_str = build_envelope(ctx)
    root = ET.fromstring(xml_str)  # Would fail if not escaped
    assert root.find("WORKING_CONTEXT").text == "x < y & z > w"

    # BB4: All fields populated → all present in output
    ctx = MemoryContext("state data", "kg topology", "learned constraints", 33.7)
    xml_str = build_envelope(ctx)
    root = ET.fromstring(xml_str)
    assert root.find("WORKING_CONTEXT").text == "state data"
    assert root.find("TOPOLOGICAL_BLAST_RADIUS").text == "kg topology"
    assert root.find("LEARNED_CONSTRAINTS").text == "learned constraints"

    # WB1: latency_ms formatted to 1 decimal place
    ctx = MemoryContext(None, None, None, 12.3456789)
    xml_str = build_envelope(ctx)
    assert "12.3</HYDRATION_LATENCY_MS>" in xml_str

    # WB2: 4 XML tags always present regardless of None fields
    ctx = MemoryContext(None, None, None, 0.0)
    xml_str = build_envelope(ctx)
    root = ET.fromstring(xml_str)
    children = list(root)
    assert len(children) == 4, f"Expected 4 children, got {len(children)}"

    # WB3: Empty string treated differently from None
    ctx = MemoryContext("", None, None, 1.0)
    xml_str = build_envelope(ctx)
    assert "Cold start. No prior state." in xml_str  # Empty string → fallback

    print("ALL TESTS PASSED — Story 2.05 (Track B)")


if __name__ == "__main__":
    test_build_envelope()
