"""SlangLang tests — written to be able to fail.
Run: python3 -m unittest discover -s ~/workspace/slanglang -v
     (or: python3 ~/workspace/slanglang/test_slanglang.py)
"""
import sys
import unittest
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))
from slanglang import (  # noqa: E402
    ACHIEVEMENT_FACES, COGNITIVE_FACES, ECOLOGY_FACES, FACE_UNITS,
    KNOWLEDGE_COMPOUNDS, KNOWLEDGE_FACES, LAB_FACES, SIGNAL_FACES,
    WORK_FACES, SlangCodec, UngrammaticalError, ValidationError,
    energy_of, expand_face, parse_canonical, parse_face_expansion,
    parse_faces, parse_message, parse_transcript, render_face_record,
    resonance_of, transcript_approved,
)

C = SlangCodec()

# Corpus: one or more normalized messages per kind.
CORPUS = [
    "!rte VER>MIR: intent.slanglang.build | ^nat | why=nathan_order | pri=hi",
    "!pro MER>MIR: build.slanglang | @p-slang1 | ^nat | do=design_and_build_the_language | pri=hi",
    "!gat+ MIR>MER: build.slanglang | @p-slang1 | ^gav | ~620",
    "!gat~ MIR>MER: build.slanglang | @p-old9 | ~340",
    "!gat~ GAV>MIR: tune.grade | @p-old8 | wait=until_bench_frees",
    "!exe MER>SYS: build.slanglang | @p-slang1 | ^gat:g-slang1~620 | do=build_the_package",
    "!vrd VED>WIT: build.slanglang | @p-slang1 | out=p | aud=980",
    "!vrd GAV>MIR: foreign.answer | @q-77 | out=c | aud=1000 | note=load_bearing_claim_flagged",
    "!rct WIT>MIR: build.slanglang | @p-slang1 | prob=no_typed_agent_language | att=ad_hoc_strings_in_notes | worked=grammar_first_design | rsn=meaning_must_survive_the_human_record",
    "!qry MIR>VED: build.slanglang | ^mir | q=does_the_grammar_reject_refusal",
    "!ans VED>MIR: build.slanglang | @p-slang1 | a=yes_by_construction",
    "!hnd MER>VED: build.slanglang | @p-slang1 | next=audit_the_package",
    "!rea MED>WIT: campaign.emerald.hoenn | face=smile | why=warp_instrument_turns_the_grind_into_survey | whynot=everything_past_oldale_is_still_stock",
    "!rea PYR>WIT: frontier.identity-term | face=frown | why=companions_attach_five_of_five | whynot=separation_still_ties_the_proxy",
]


class RoundTrip(unittest.TestCase):
    def test_slang_canonical_slang_is_stable(self):
        for line in CORPUS:
            with self.subTest(line=line):
                msg = parse_message(line)
                self.assertEqual(parse_canonical(msg.to_canonical()).to_slang(), line)

    def test_canonical_slang_canonical_is_stable(self):
        for line in CORPUS:
            with self.subTest(line=line):
                canon = parse_message(line).to_canonical()
                self.assertEqual(parse_canonical(canon).to_canonical(), canon)

    def test_field_order_is_normalized(self):
        shuffled = ("!pro MER>MIR: build.slanglang | pri=hi | "
                    "do=design_and_build_the_language | ^nat | @p-slang1")
        self.assertEqual(parse_message(shuffled).to_slang(), CORPUS[1])

    def test_expansion_is_deterministic(self):
        for line in CORPUS:
            m = parse_message(line)
            self.assertEqual(m.to_canonical(), m.to_canonical())
            self.assertEqual(m.to_slang(), parse_message(m.to_slang()).to_slang())


class RefusalIsAbsence(unittest.TestCase):
    def test_there_is_no_refusal_kind(self):
        for bad in ("!gat- MIR>MER: x.y | @p-1 | ~100",
                    "!ref GAV>MIR: x.y | @p-1",
                    "!rej GAV>MIR: x.y | @p-1"):
            with self.subTest(bad=bad), self.assertRaises(UngrammaticalError):
                parse_message(bad)

    def test_approval_below_eta_half_is_ungrammatical(self):
        with self.assertRaises(UngrammaticalError):
            parse_message("!gat+ MIR>MER: x.y | @p-1 | ~499")
        with self.assertRaises(UngrammaticalError):
            parse_message("!gat+ GAV>MIR: x.y | @p-1 | ~320")
        with self.assertRaises(UngrammaticalError):
            C.approve("MIR", "MER", "x.y", ref="p-1", eta=320)

    def test_defer_at_approval_eta_is_ungrammatical(self):
        with self.assertRaises(UngrammaticalError):
            parse_message("!gat~ MIR>MER: x.y | @p-1 | ~620")

    def test_execution_without_gate_token_cannot_be_written(self):
        with self.assertRaises((UngrammaticalError, ValidationError)):
            parse_message("!exe MER>SYS: x.y | @p-1 | do=run_it")
        with self.assertRaises(UngrammaticalError):
            C.execute("MER", "SYS", "x.y", ref="p-1", gate_id="g-1",
                      gate_eta=320, do="run_it")

    def test_execution_with_weak_gate_token_cannot_be_written(self):
        with self.assertRaises(UngrammaticalError):
            parse_message("!exe MER>SYS: x.y | @p-1 | ^gat:g-1~320 | do=run_it")

    def test_codec_has_no_refusal_surface(self):
        self.assertFalse(hasattr(C, "refuse"))
        self.assertFalse(hasattr(C, "reject"))
        self.assertFalse(hasattr(C, "deny"))

    def test_unapproved_proposal_is_refused_by_absence(self):
        msgs = parse_transcript(
            "rise\n"
            "!pro MER>MIR: x.y | @p-1 | ^nat | do=run_it\n"
            "fall")
        self.assertFalse(transcript_approved(msgs, "p-1"))
        msgs2 = parse_transcript(
            "rise\n"
            "!pro MER>MIR: x.y | @p-1 | ^nat | do=run_it\n"
            "!gat+ MIR>MER: x.y | @p-1 | ~620\n"
            "fall")
        self.assertTrue(transcript_approved(msgs2, "p-1"))


class React(unittest.TestCase):
    SMILE = CORPUS[-2]
    FROWN = CORPUS[-1]

    def test_react_expands_to_a_complete_verdict_sentence(self):
        canon = parse_message(self.SMILE).to_canonical()
        self.assertEqual(
            canon,
            'Meridian reacts to Witness: subject "campaign.emerald.hoenn". '
            "Reaction: smile 😊. Reason: warp instrument turns the grind "
            "into survey. Why not: everything past oldale is still stock.")

    def test_react_frown_glyph_expands(self):
        canon = parse_message(self.FROWN).to_canonical()
        self.assertIn("Reaction: frown ☹️.", canon)
        self.assertIn("Pyrrho reacts to Witness", canon)
        self.assertIn("Why not: separation still ties the proxy.", canon)

    def test_react_missing_grounds_cannot_be_written(self):
        for bad in ("!rea MED>WIT: x.y | face=smile | whynot=b",  # no why
                    "!rea MED>WIT: x.y | face=smile | why=a",  # no whynot
                    "!rea MED>WIT: x.y | why=a | whynot=b"):  # no face
            with self.subTest(bad=bad), self.assertRaises(ValidationError):
                parse_message(bad)
        with self.assertRaises(ValidationError):
            C.react("MED", "WIT", "x.y", face="smile", why="a", whynot="")

    def test_react_unknown_glyph_is_rejected(self):
        with self.assertRaises(ValidationError):
            parse_message("!rea MED>WIT: x.y | face=shrug | why=a | whynot=b")
        with self.assertRaises(UngrammaticalError):
            parse_canonical('Meridian reacts to Witness: subject "x.y". '
                            "Reaction: shrug. Reason: a. Why not: b.")

    def test_react_provenance_rides_the_grammar(self):
        line = ("!rea MED>WIT: campaign.emerald.hoenn | ^wit | face=smile | "
                "why=warp_instrument_turns_the_grind_into_survey | "
                "whynot=everything_past_oldale_is_still_stock")
        msg = parse_message(line)
        self.assertEqual(msg.prov, "wit")
        canon = msg.to_canonical()
        self.assertTrue(canon.endswith("Provenance: Witness."))
        self.assertEqual(parse_canonical(canon).to_slang(), line)

    def test_react_codec_round_trip(self):
        msg = C.react("MED", "WIT", "campaign.emerald.hoenn", face="smile",
                      why="warp_instrument_turns_the_grind_into_survey",
                      whynot="everything_past_oldale_is_still_stock")
        self.assertEqual(msg.to_slang(), self.SMILE)
        self.assertEqual(parse_message(msg.to_slang()), msg)
        self.assertEqual(parse_canonical(msg.to_canonical()).to_slang(),
                         self.SMILE)


class FaceSchema(unittest.TestCase):
    # The Face Schema tables (N8toriousAi's schema, adopted 2026-11-05
    # 07:16), hard-coded here so the suite fails if the implementation
    # drifts from the adopted definitions.
    COGNITIVE = {
        "😀": "agrees",
        "🤔": "uncertain",
        "🧐": "investigating",
        "😮": "discovery",
        "😤": "disagreement",
        "😬": "regression",
        "🤝": "consensus",
        "😎": "verified",
        "🧠": "principle found",
        "🙃": "unexpected side effect",
        "😴": "dormant",
    }
    WORK = {
        "🔨": "working",
        "🧱": "blocked",
        "🚪": "waiting on gate",
        "🅿️": "parked",
        "📦": "staged",
        "🚢": "shipped",
        "🧊": "frozen",
        "📐": "measuring",
        "🏗️": "building infrastructure",
        "♻️": "refactoring",
        "🔬": "experiment active",
    }
    SIGNAL = {
        "⚠️": "warning",
        "👀": "needs your eye",
        "📸": "snapshot filed",
        "🧾": "receipt filed",
        "📤": "handoff sent",
        "🔁": "retrying",
        "📱": "device pending",
        "🐛": "defect found",
        "📚": "pattern recorded",
        "🗂️": "promoted",
        "📍": "landmark identified",
        "🎯": "target reached",
    }
    ACHIEVEMENT = {
        "🔥": "major improvement",
        "🏆": "best result so far",
        "👑": "new baseline",
        "🚀": "major efficiency gain",
        "💎": "rare discovery",
        "🌱": "first successful attempt",
        "🏛️": "canonized",
        "🤯": "breakthrough",
        "🧩": "new pattern discovered",
    }
    KNOWLEDGE = {
        "🪵": "wood principle",
        "🪨": "stone principle",
        "🌊": "water principle",
        "🪟": "glass principle",
        "🧵": "cloth principle",
        "⚙️": "metal principle",
        "⬜": "plaster principle",
        "🍃": "foliage principle",
        "🟤": "earth principle",
        "💡": "emissive principle",
    }
    ECOLOGY = {
        "🌿": "growing",
        "🍎": "feeding",
        "🌉": "cross-pollination",
        "🕸️": "connection formed",
        "🌲": "mature capability",
    }
    TABLES = ((COGNITIVE, "cognitive"), (WORK, "work"), (SIGNAL, "signal"),
              (ACHIEVEMENT, "achievement"), (KNOWLEDGE, "knowledge"),
              (ECOLOGY, "ecology"))
    # Glyphs tabled WITH U+FE0F, built from escapes so the exact
    # codepoints are pinned here independent of any editor.
    VS16 = {"⚠️": "warning", "🅿️": "parked",
            "♻️": "refactoring",
            "🏗️": "building infrastructure",
            "🗂️": "promoted", "⚙️": "metal principle",
            "🕸️": "connection formed",
            "🏛️": "canonized"}
    VS16_BARE = ("⚠", "🅿", "♻", "🏗",
                 "🗂", "⚙", "🕸", "🏛")

    def test_implementation_tables_are_the_schema_tables(self):
        self.assertEqual(COGNITIVE_FACES, self.COGNITIVE)
        self.assertEqual(WORK_FACES, self.WORK)
        self.assertEqual(SIGNAL_FACES, self.SIGNAL)
        self.assertEqual(ACHIEVEMENT_FACES, self.ACHIEVEMENT)
        self.assertEqual(KNOWLEDGE_FACES, self.KNOWLEDGE)
        self.assertEqual(ECOLOGY_FACES, self.ECOLOGY)

    def test_totals(self):
        self.assertEqual(len(LAB_FACES), 58)       # single faces
        self.assertEqual(len(KNOWLEDGE_COMPOUNDS), 20)
        self.assertEqual(len(FACE_UNITS), 78)      # + compounds
        self.assertEqual({tier for tier, _ in LAB_FACES.values()},
                         {"cognitive", "work", "signal", "achievement",
                          "knowledge", "ecology"})

    def test_every_face_expands_exactly_with_its_tier(self):
        for table, tier in self.TABLES:
            for glyph, meaning in table.items():
                with self.subTest(glyph=glyph):
                    self.assertEqual(expand_face(glyph), meaning)
                    self.assertEqual(parse_faces(glyph).expand(), meaning)
                    self.assertEqual(parse_faces(glyph).tiers, (tier,))

    def test_meanings_unique_across_all_units(self):
        # The reverse map is exact only if no meaning is ever duplicated
        # — the Face Schema Law's uniqueness clause, proven not asserted.
        meanings = [m for _, m in FACE_UNITS.values()]
        self.assertEqual(len(meanings), len(set(meanings)))

    def test_every_unit_round_trips_both_directions(self):
        for unit in FACE_UNITS:
            with self.subTest(unit=unit):
                one = parse_faces(unit)
                self.assertEqual(one.to_wire(), unit)
                self.assertEqual(parse_face_expansion(one.expand()), one)
                self.assertEqual(
                    parse_face_expansion(one.expand()).expand(), one.expand())

    def test_variation_selector_is_part_of_the_glyph(self):
        for glyph, meaning in self.VS16.items():
            with self.subTest(glyph=glyph):
                self.assertIn(glyph, LAB_FACES)
                self.assertEqual(expand_face(glyph), meaning)
        for bare in self.VS16_BARE:
            with self.subTest(bare=bare), self.assertRaises(UngrammaticalError):
                parse_faces(bare)

    def test_unknown_face_is_rejected_never_guessed(self):
        for bad in ("🦄", "🙂", "", "   ", "🏆😎"):
            with self.subTest(bad=bad), self.assertRaises(UngrammaticalError):
                parse_faces(bad)
            with self.subTest(bad=bad), self.assertRaises(UngrammaticalError):
                expand_face(bad)
        with self.assertRaises(UngrammaticalError):
            parse_face_expansion("world domination")
        with self.assertRaises(UngrammaticalError):
            parse_face_expansion("investigating → world domination")

    def test_codec_surface_covers_the_schema(self):
        fc = C.parse_faces("🚪 → 🔨 → 📱")
        self.assertEqual(C.expand_faces(fc),
                         "waiting on gate → working → device pending")
        self.assertEqual(
            C.parse_face_expansion(
                "waiting on gate → working → device pending"), fc)


class Supersession(unittest.TestCase):
    # The schema adoption (2026-11-05 07:16) superseded specific parts
    # of the annex's first version. These tests pin the NEW law and the
    # death of the old: nothing from the earlier tables survives by
    # accident, and nothing vanished silently — it is all on record in
    # SPEC Annex A's supersession record.

    def test_trophy_stands_alone_now(self):
        fc = parse_faces("🏆")
        self.assertEqual(fc.expand(), "best result so far")
        self.assertEqual(fc.tiers, ("achievement",))
        self.assertEqual(parse_face_expansion("best result so far").faces,
                         ("🏆",))

    def test_crown_is_the_new_baseline(self):
        self.assertEqual(expand_face("👑"), "new baseline")
        self.assertEqual(parse_face_expansion("new baseline").faces, ("👑",))

    def test_the_old_bound_pair_is_dissolved(self):
        # 🏆😎 as one face no longer exists: adjacency is not a unit.
        with self.assertRaises(UngrammaticalError):
            parse_faces("🏆😎")
        # Written as two faces, it says two different things now.
        self.assertEqual(parse_faces("🏆 → 😎").expand(),
                         "best result so far → verified")

    def test_superseded_meanings_no_longer_expand_back(self):
        for old in ("promoted to baseline", "target achieved",
                    "validated success", "regression detected",
                    "consensus reached", "unexpected discovery",
                    "needs nathan's eye", "performance gain"):
            with self.subTest(old=old), self.assertRaises(UngrammaticalError):
                parse_face_expansion(old)

    def test_target_lives_in_signals_only(self):
        fc = parse_faces("🎯")
        self.assertEqual(fc.tiers, ("signal",))
        self.assertEqual(fc.expand(), "target reached")
        self.assertNotIn("🎯", ACHIEVEMENT_FACES)

    def test_old_tier_names_are_gone(self):
        tiers = {tier for tier, _ in LAB_FACES.values()}
        self.assertNotIn("conversation", tiers)
        self.assertNotIn("lane", tiers)


class KnowledgeCompounds(unittest.TestCase):
    MATERIALS = (("🪵", "wood"), ("🪨", "stone"), ("🌊", "water"),
                 ("🪟", "glass"), ("🧵", "cloth"), ("⚙️", "metal"),
                 ("⬜", "plaster"), ("🍃", "foliage"), ("🟤", "earth"),
                 ("💡", "emissive"))

    def _expected(self):
        out = {}
        for glyph, material in self.MATERIALS:
            out[glyph + "🧠"] = f"{material} lesson discovered"
            out[glyph + "🏛️"] = f"{material} treatment canonized"
        return out

    def test_compound_table_matches_the_schema_examples_generalized(self):
        self.assertEqual(KNOWLEDGE_COMPOUNDS, self._expected())

    def test_nathans_two_examples_exactly(self):
        self.assertEqual(expand_face("🪨🧠"), "stone lesson discovered")
        self.assertEqual(expand_face("🪵🏛️"), "wood treatment canonized")
        self.assertEqual(parse_faces("🪨🧠").faces, ("🪨🧠",))
        self.assertEqual(parse_faces("🪵🏛️").tiers, ("knowledge",))

    def test_every_compound_round_trips(self):
        for unit, meaning in self._expected().items():
            with self.subTest(unit=unit):
                self.assertEqual(parse_faces(unit).expand(), meaning)
                self.assertEqual(parse_face_expansion(meaning).faces, (unit,))

    def test_binding_is_scoped_to_the_two_qualifiers(self):
        # A Tier V glyph binds ONLY to 🧠 / 🏛️. Every other adjacency
        # is in no table and is rejected.
        for bad in ("🪨🔥", "🧠🪨", "🪨🧐", "🌊📚", "🪨😀", "🏛️🪵"):
            with self.subTest(bad=bad), self.assertRaises(UngrammaticalError):
                parse_faces(bad)

    def test_compound_inside_a_chain(self):
        fc = parse_faces("🧐 → 🪵🏛️ → 📚")
        self.assertEqual(fc.faces, ("🧐", "🪵🏛️", "📚"))
        self.assertEqual(
            fc.expand(),
            "investigating → wood treatment canonized → pattern recorded")
        self.assertEqual(parse_face_expansion(fc.expand()), fc)

    def test_compound_is_not_the_spaced_pair(self):
        # Adjacency binds (one link, the compound meaning); a separator
        # makes two links with their own meanings. Different claims.
        bound = parse_faces("🪨🧠")
        spaced = parse_faces("🪨 🧠")
        self.assertEqual(len(bound), 1)
        self.assertEqual(len(spaced), 2)
        self.assertEqual(spaced.expand(),
                         "stone principle → principle found")
        self.assertNotEqual(bound.expand(), spaced.expand())


class TierVCompletion(unittest.TestCase):
    # The last four knowledge seats, filled by N8toriousAi's adopted slate
    # (2026-11-05 07:56): ⬜ 🍃 🟤 💡. ⬜'s caveat — no glyph literally
    # means plaster — is spec record (Annex A), not something a test
    # can soften; what the tests pin is that the slate landed exactly.
    NEW_SEATS = {"⬜": "plaster", "🍃": "foliage",
                 "🟤": "earth", "💡": "emissive"}

    def test_new_seats_expand_exactly(self):
        for glyph, material in self.NEW_SEATS.items():
            with self.subTest(glyph=glyph):
                self.assertEqual(expand_face(glyph), f"{material} principle")
                self.assertEqual(parse_faces(glyph).tiers, ("knowledge",))

    def test_new_seat_compounds_named(self):
        # The template generates both compounds per new material; the
        # eight are named here so the slate's compounds are pinned
        # individually, not only by the generalized table test.
        for glyph, material in self.NEW_SEATS.items():
            with self.subTest(glyph=glyph):
                self.assertEqual(expand_face(glyph + "🧠"),
                                 f"{material} lesson discovered")
                self.assertEqual(expand_face(glyph + "🏛️"),
                                 f"{material} treatment canonized")
                self.assertEqual(
                    parse_face_expansion(f"{material} lesson discovered").faces,
                    (glyph + "🧠",))
                self.assertEqual(
                    parse_face_expansion(
                        f"{material} treatment canonized").faces,
                    (glyph + "🏛️",))

    def test_new_seat_boundaries(self):
        # The adoption conditions, as separations: 🍃 is the MATERIAL,
        # 🌿 is the crew growing; 🟤 is the soil, 🌱 is the sprout of a
        # first attempt; 💡 is a light-EMITTING surface, 🔥 is a result.
        self.assertEqual(parse_faces("🍃").tiers, ("knowledge",))
        self.assertEqual(parse_faces("🌿").tiers, ("ecology",))
        self.assertNotEqual(expand_face("🍃"), expand_face("🌿"))
        self.assertEqual(parse_faces("🟤").tiers, ("knowledge",))
        self.assertEqual(parse_faces("🌱").tiers, ("achievement",))
        self.assertNotEqual(expand_face("🟤"), expand_face("🌱"))
        self.assertEqual(parse_faces("💡").tiers, ("knowledge",))
        self.assertEqual(parse_faces("🔥").tiers, ("achievement",))
        self.assertNotEqual(expand_face("💡"), expand_face("🔥"))


class ChainSeparators(unittest.TestCase):
    # N8toriousAi's worked example, as he wrote it (spaces, 2026-11-05):
    NATHAN_SPACED = "🧐 🔬 🐛 🔁 📐 👀 🔥 📚 🗂️ 👑 🏛️"
    NATHAN_ARROW = "🧐 → 🔬 → 🐛 → 🔁 → 📐 → 👀 → 🔥 → 📚 → 🗂️ → 👑 → 🏛️"
    NATHAN_EXPANSION = (
        "investigating → experiment active → defect found → retrying "
        "→ measuring → needs your eye → major improvement "
        "→ pattern recorded → promoted → new baseline → canonized")
    NATHAN_TIERS = ("cognitive", "work", "signal", "signal", "work",
                    "signal", "achievement", "signal", "signal",
                    "achievement", "achievement")

    def test_nathans_worked_example_in_his_space_form(self):
        fc = parse_faces(self.NATHAN_SPACED)
        self.assertEqual(len(fc), 11)
        self.assertEqual(fc.expand(), self.NATHAN_EXPANSION)
        self.assertEqual(fc.tiers, self.NATHAN_TIERS)

    def test_space_and_arrow_forms_are_the_same_chain(self):
        self.assertEqual(parse_faces(self.NATHAN_SPACED),
                         parse_faces(self.NATHAN_ARROW))

    def test_emission_is_the_canonical_arrow_form(self):
        # Round-trip is exact against the canonical form: space input
        # normalizes to arrows on emission, as field order normalizes.
        fc = parse_faces(self.NATHAN_SPACED)
        self.assertEqual(fc.to_wire(), self.NATHAN_ARROW)
        self.assertEqual(parse_faces(fc.to_wire()), fc)
        self.assertEqual(parse_face_expansion(fc.expand()), fc)
        self.assertEqual(parse_face_expansion(fc.expand()).to_wire(),
                         self.NATHAN_ARROW)

    def test_mixed_separators_parse(self):
        fc = parse_faces("🧐 🔬 → 🐛")
        self.assertEqual(fc.faces, ("🧐", "🔬", "🐛"))
        self.assertEqual(fc.to_wire(), "🧐 → 🔬 → 🐛")

    def test_empty_links_are_rejected(self):
        for bad in ("🧐 →", "→ 🧐", "🧐 →  → 🔥", "→"):
            with self.subTest(bad=bad), self.assertRaises(UngrammaticalError):
                parse_faces(bad)


class CompositionLaw(unittest.TestCase):
    def test_chain_across_all_six_tiers(self):
        # C1: any tier may open a chain, any tier may close one.
        fc = parse_faces("😴 → 🏗️ → 📍 → 🌱 → 🪨 → 🌉")
        self.assertEqual(fc.tiers, ("cognitive", "work", "signal",
                                    "achievement", "knowledge", "ecology"))
        self.assertEqual(
            fc.expand(),
            "dormant → building infrastructure → landmark identified "
            "→ first successful attempt → stone principle "
            "→ cross-pollination")
        self.assertEqual(parse_face_expansion(fc.expand()), fc)

    def test_single_face_is_a_chain_of_length_one(self):
        fc = parse_faces("👑")
        self.assertEqual(len(fc), 1)
        self.assertEqual(fc.expand(), "new baseline")

    def test_repeated_face_means_recurrence(self):
        # C4: the chain is a history, not a set.
        fc = parse_faces("🧱 → 🔨 → 🧱")
        self.assertEqual(fc.expand(), "blocked → working → blocked")
        self.assertEqual(parse_face_expansion(fc.expand()), fc)

    def test_adjacent_glyphs_without_separator_are_not_a_chain(self):
        # C3: glyphs do not concatenate (knowledge compounds aside).
        for bad in ("🔥👑", "🔨🔨", "🧐🧐", "📦🚢", "🌿🌲", "🏆😎"):
            with self.subTest(bad=bad), self.assertRaises(UngrammaticalError):
                parse_faces(bad)

    def test_worked_morning_chain_from_the_annex(self):
        # Annex A's worked example under the schema: same morning, the
        # one meaning the schema changed (👀) expands in its new form.
        wire = "🧐 → 🚪 → 🔨 → 🐛 → 🔁 → 📐 → 👀 → 🔥 → 📦"
        fc = parse_faces(wire)
        self.assertEqual(
            fc.expand(),
            "investigating → waiting on gate → working → defect found "
            "→ retrying → measuring → needs your eye "
            "→ major improvement → staged")
        self.assertEqual(fc.tiers, ("cognitive", "work", "work", "signal",
                                    "signal", "work", "signal",
                                    "achievement", "work"))
        self.assertEqual(parse_face_expansion(fc.expand()), fc)


class AuthorityAndRefusals(unittest.TestCase):
    # Annex A, considered and refused — none of these may ever parse.
    REFUSED = ("✅", "❌", "👍", "🛑", "🔒", "🧪", "💤", "⏳", "🎉")

    def test_refused_glyphs_are_rejected(self):
        for glyph in self.REFUSED:
            with self.subTest(glyph=glyph), self.assertRaises(UngrammaticalError):
                parse_faces(glyph)
            with self.subTest(glyph=glyph), self.assertRaises(UngrammaticalError):
                expand_face(glyph)
            with self.subTest(glyph=glyph), self.assertRaises(UngrammaticalError):
                parse_faces(f"🧐 → {glyph}")

    def test_face_layer_stays_disjoint_from_rea(self):
        # A chain summarizes traffic; it can never carry a reaction's
        # grounds, and rea's glyphs can never be smuggled in as faces.
        self.assertFalse(set(FACE_UNITS) & {"😊", "☹️"})
        with self.assertRaises(UngrammaticalError):
            parse_faces("😊 → 🔥")
        with self.assertRaises(UngrammaticalError):
            parse_faces("🔥 → ☹️")

    def test_faces_confer_no_authority(self):
        # Shipped, frozen, waiting, promoted, canonized, crowned: all
        # report state, none of them approves anything.
        msgs = parse_transcript(
            "rise\n"
            "!pro MER>MIR: x.y | @p-1 | ^nat | do=run_it\n"
            "fall")
        for wire in ("🚢", "🚪", "📱", "🧊", "🗂️", "🏛️", "👑"):
            with self.subTest(wire=wire):
                self.assertTrue(parse_faces(wire).expand())
                self.assertFalse(transcript_approved(msgs, "p-1"))
        # The codec's face surface is parse/expand/record only — no
        # face-shaped approve, ship, freeze, promote, or canonize verb.
        for verb in ("ship", "freeze", "publish", "promote", "canonize",
                     "approve_face"):
            self.assertFalse(hasattr(C, verb))

    def test_a_face_is_not_a_message(self):
        for glyph in ("👑", "🏛️", "🧠"):
            with self.subTest(glyph=glyph), self.assertRaises(UngrammaticalError):
                parse_message(glyph)


class LogTransparency(unittest.TestCase):
    # N8toriousAi's order (2026-11-05 07:16): the faces are visible INSIDE
    # the log — the filed record carries the raw glyphs beside the
    # expansion, glyph-first, byte-exact. Nothing strips them.

    def test_record_is_glyph_first_expansion_after(self):
        fc = parse_faces("🧐 → 🔥")
        rec = fc.to_record()
        lines = rec.split("\n")
        self.assertEqual(len(lines), 2)
        self.assertEqual(lines[0], fc.to_wire())   # glyphs first
        self.assertEqual(lines[1], fc.expand())    # expansion after
        self.assertEqual(render_face_record(fc), rec)
        self.assertEqual(C.face_record(fc), rec)

    def test_every_unit_survives_the_record_byte_identical(self):
        for unit in FACE_UNITS:
            with self.subTest(unit=unit):
                rec = parse_faces(unit).to_record()
                self.assertIn(unit.encode("utf-8"), rec.encode("utf-8"))
                glyph_line = rec.split("\n")[0]
                self.assertEqual(glyph_line, unit)
                self.assertEqual(parse_faces(glyph_line), parse_faces(unit))

    def test_new_seat_glyphs_survive_the_record_byte_exact(self):
        # N8toriousAi's slate (⬜ 🍃 🟤 💡) and its compounds, through the
        # log-transparency path: glyph line raw and byte-identical,
        # re-parsing to the same chain, and no ASCII form exists.
        units = ("⬜", "🍃", "🟤", "💡",
                 "⬜🧠", "🍃🏛️", "🟤🧠", "💡🏛️")
        for unit in units:
            with self.subTest(unit=unit):
                rec = parse_faces(unit).to_record()
                self.assertIn(unit.encode("utf-8"), rec.encode("utf-8"))
                glyph_line, expansion_line = rec.split("\n")
                self.assertEqual(glyph_line, unit)
                self.assertEqual(parse_faces(glyph_line), parse_faces(unit))
                self.assertEqual(parse_face_expansion(expansion_line),
                                 parse_faces(unit))
                with self.assertRaises(UnicodeEncodeError):
                    rec.encode("ascii")

    def test_variation_selectors_survive_byte_exact(self):
        for glyph in FaceSchema.VS16:
            with self.subTest(glyph=glyph):
                rec = parse_faces(glyph).to_record()
                self.assertIn("️".encode("utf-8"),
                              rec.encode("utf-8"))
                self.assertEqual(rec.split("\n")[0], glyph)

    def test_worked_example_record_shows_all_glyphs_and_meanings(self):
        fc = parse_faces(ChainSeparators.NATHAN_SPACED)
        rec = fc.to_record()
        for glyph in ("🧐", "🔬", "🐛", "🔁", "📐", "👀", "🔥", "📚",
                      "🗂️", "👑", "🏛️"):
            self.assertIn(glyph, rec)
        for meaning in ("investigating", "experiment active",
                        "defect found", "retrying", "measuring",
                        "needs your eye", "major improvement",
                        "pattern recorded", "promoted", "new baseline",
                        "canonized"):
            self.assertIn(meaning, rec)
        # And the record's two lines each re-parse to the same chain.
        glyph_line, expansion_line = rec.split("\n")
        self.assertEqual(parse_faces(glyph_line), fc)
        self.assertEqual(parse_face_expansion(expansion_line), fc)

    def test_ascii_folding_fails_loudly_never_silently(self):
        fc = parse_faces("🧐 → 🔥")
        # There is no ASCII form of a glyph-bearing rendering: encoding
        # one raises, it does not degrade.
        with self.assertRaises(UnicodeEncodeError):
            fc.to_wire().encode("ascii")
        with self.assertRaises(UnicodeEncodeError):
            fc.to_record().encode("ascii")
        # A glyph-stripped line is not a face record and does not parse.
        with self.assertRaises(UngrammaticalError):
            parse_faces("? → ?")
        with self.assertRaises(UngrammaticalError):
            parse_faces(fc.expand())  # words alone are not the record

    def test_record_round_trip_through_plain_text(self):
        wire = "🧐 → 🪨🧠 → 📚 → 🏛️"
        fc = parse_faces(wire)
        rec = fc.to_record()
        glyph_line, expansion_line = rec.split("\n")
        self.assertEqual(glyph_line, wire)
        self.assertEqual(parse_faces(glyph_line).to_record(), rec)
        self.assertEqual(parse_face_expansion(expansion_line), fc)


class Malformed(unittest.TestCase):
    def test_rejections(self):
        bad = [
            "",  # empty
            "pro MER>MIR: x.y | @p-1 | ^nat | do=run_it",  # no '!'
            "!pro MER>MIR x.y | @p-1 | ^nat | do=run_it",  # no colon
            "!pro MER>ZZZ: x.y | @p-1 | ^nat | do=run_it",  # unknown agent
            "!pro MER>MIR: X.y | @p-1 | ^nat | do=run_it",  # subject case
            "!pro MER>MIR: x.y | @p-1 | ^nat",  # missing do=
            "!pro MER>MIR: x.y | do=run_it",  # pro without @id / provenance
            "!pro MER>MIR: x.y | @p-1 | ^nat | do=run_it | zzz=1",  # unknown key
            "!pro MER>MIR: x.y | @p-1 | ^nat | do=run it",  # space in value
            "!gat+ MIR>MER: x.y | @p-1 | ~1001",  # eta out of range
            "!gat+ MIR>MER: x.y | @p-1 | ~62",  # eta not milli-padded
            "!rte MIR>VED: x.y | why=test",  # only Vera routes
            "!exe VED>SYS: x.y | @p-1 | ^gat:g-1~620 | do=run_it",  # only Merlin executes
            "!rct VED>MIR: x.y | @p-1 | prob=a | att=b | worked=c | rsn=d",  # only Witness receipts
            "!vrd VED>WIT: x.y | @p-1 | out=x | aud=500",  # bad outcome enum
            "!vrd VED>WIT: x.y | @p-1 | out=p | aud=1001",  # audit out of range
            "!qry MIR>VED: x.y | q=what | ^gat:g-1~620",  # gate token outside exe
        ]
        for line in bad:
            with self.subTest(line=line), self.assertRaises(
                    (UngrammaticalError, ValidationError)):
                parse_message(line)

    def test_transcript_requires_envelope(self):
        with self.assertRaises(UngrammaticalError):
            parse_transcript("!qry MIR>VED: x.y | q=what")
        with self.assertRaises(UngrammaticalError):
            parse_transcript("rise\n!qry MIR>VED: x.y | q=what")  # no fall


class EnergyLineage(unittest.TestCase):
    def test_alphabet_law_inherited_exactly(self):
        # RaijinLang 17: value = alphabet index * (5 vowel / 2 consonant)
        self.assertEqual(energy_of("storm"), 215)   # matches 17's chassis
        self.assertEqual(energy_of("fall"), 65)
        self.assertEqual(energy_of("echo"), 122)
        self.assertEqual(energy_of("pulse"), 224)
        self.assertEqual(energy_of(""), 0)
        self.assertEqual(resonance_of(""), 0.0)

    def test_quanta_is_a_measure_not_a_meaning(self):
        # Two messages with identical typed content but different subjects
        # carry different quanta; the MEANING (kind/fields) is unchanged.
        a = parse_message(CORPUS[0])
        b = parse_message("!rte VER>MIR: intent.other.thing | why=nathan_order | pri=hi | ^nat")
        self.assertNotEqual(a.quanta, b.quanta)
        self.assertEqual((a.kind, a.fields), (b.kind, b.fields))


class CanonicalForm(unittest.TestCase):
    def test_canonical_rejects_free_prose(self):
        with self.assertRaises(UngrammaticalError):
            parse_canonical("Merlin proposes something, roughly, to Mira.")

    def test_every_kind_expands_to_its_speaker_and_kind(self):
        for line in CORPUS:
            canon = parse_message(line).to_canonical()
            self.assertTrue(canon.endswith("."))
            self.assertIn(parse_message(line).src and
                          __import__("slanglang").AGENTS[parse_message(line).src],
                          canon)


if __name__ == "__main__":
    unittest.main(verbosity=2)
