"""
Genesis Persistent Context Architecture — ZERO_AMNESIA_STATE Envelope
Story 2.05 — Track B

Assembles the XML envelope that gets injected into every LLM system prompt.
Ensures every LLM call starts with full memory context.
"""
from dataclasses import dataclass
from typing import Optional
from xml.sax.saxutils import escape


@dataclass
class MemoryContext:
    """Context assembled from 3-layer scatter-gather."""
    working_state: Optional[str]
    kg_topology: Optional[str]
    learned_constraints: Optional[str]
    latency_ms: float


# Canonical fallback strings for None fields
FALLBACK_WORKING = "Cold start. No prior state."
FALLBACK_KG = "No KG context available."
FALLBACK_CONSTRAINTS = "No prior scars for this task type."


def build_envelope(context: MemoryContext) -> str:
    """
    Assemble the <ZERO_AMNESIA_STATE> XML envelope from a MemoryContext.

    Args:
        context: MemoryContext with fields from scatter-gather

    Returns:
        Valid XML string parseable by xml.etree.ElementTree.fromstring()
        All None fields replaced with canonical fallback strings.
        Empty string fields also replaced with canonical fallback strings.
        XML special characters in content are escaped.
    """
    working = escape(context.working_state or FALLBACK_WORKING)
    kg = escape(context.kg_topology or FALLBACK_KG)
    constraints = escape(context.learned_constraints or FALLBACK_CONSTRAINTS)
    latency = f"{context.latency_ms:.1f}"

    return (
        f"<ZERO_AMNESIA_STATE>"
        f"<WORKING_CONTEXT>{working}</WORKING_CONTEXT>"
        f"<TOPOLOGICAL_BLAST_RADIUS>{kg}</TOPOLOGICAL_BLAST_RADIUS>"
        f"<LEARNED_CONSTRAINTS>{constraints}</LEARNED_CONSTRAINTS>"
        f"<HYDRATION_LATENCY_MS>{latency}</HYDRATION_LATENCY_MS>"
        f"</ZERO_AMNESIA_STATE>"
    )

# VERIFICATION_STAMP
# Story: 2.05 (Track B)
# Verified By: parallel-builder
# Verified At: 2026-02-25T00:00:00Z
# Tests: 7/7
# Coverage: 100%
