# Copyright (c) 2026 CoreStory, Inc.
# SPDX-License-Identifier: Apache-2.0
"""Contracts for the Garden display projection and deterministic output."""
from collections import Counter
from html.parser import HTMLParser
import hashlib
import json
from pathlib import Path
import unittest

from rdflib import Graph, RDF, RDFS
from scripts.build_rdf import ROOT, assemble, turtle
from scripts.catalog import catalog
from scripts.site_projection import project


class RepositoryRedirectTests(unittest.TestCase):
    def check_redirect(self, mount):
        import tempfile
        from unittest.mock import patch
        from scripts.build_site import build
        with tempfile.TemporaryDirectory() as directory:
            output = Path(directory) / 'site'
            # Vendor copying is unrelated; exercise the real complete renderer.
            with patch('scripts.build_site.copy_garden'):
                build(output, Path(directory), ROOT / 'dist', base_path=mount)
            redirect = output / '_redirects'
            self.assertTrue(redirect.is_file(), 'Missing provider repository redirect')
            self.assertEqual(redirect.read_text(), mount + 'repo https://github.com/CoreStoryAI/ontologies 302\n')
            self.assertFalse((output / '_worker.js').exists())

    def test_root_exact_repository_redirect(self):
        self.check_redirect('/')

    def test_subpath_does_not_capture_host_root(self):
        self.check_redirect('/ontologies/')


class SiteProjectionTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.payload, cls.metadata = project()
        cls.classes = {c["id"]: c for c in cls.payload[0]["concepts"]}
        cls.properties = {p["id"]: p for p in cls.payload[1]["concepts"]}

    def test_requirement_definition_is_normative(self):
        node = self.classes["https://ontologies.corestory.ai/specspec/Requirement"]
        constraint = next(p for p in node["shape"][0] if p["property"].endswith("/statement_mode"))
        self.assertEqual(constraint["min"], 1)
        self.assertEqual(constraint["max"], 1)
        self.assertEqual(constraint["shape"], [{"@value": "normative"}])
        self.assertIn("reviewer", node["remarks"]["en"])

    def test_bridge_points_to_both_ontologies(self):
        node = self.classes["https://ontologies.corestory.ai/specspec/sao/RequirementImplementationLink"]
        ranges = {r for p in node["shape"][0] for option in p.get("shape", [])
                  if isinstance(option, list) for r in option}
        self.assertIn("https://ontologies.corestory.ai/specspec/Requirement", ranges)
        self.assertIn("https://ontologies.corestory.ai/sao/CallableUnit", ranges)

    def test_inverse_and_retirement_explanations_are_present(self):
        prop = self.properties["https://ontologies.corestory.ai/sao/invokes_callables"]
        self.assertIn("OWL inverse:", prop["remarks"]["en"])
        retired = [p for p in self.properties.values() if p.get("deprecated")]
        self.assertEqual(len(retired), 9)
        self.assertTrue(all(p.get("remarks") for p in retired))

    def test_datastore_allowed_values_appear_once(self):
        node = self.classes["https://ontologies.corestory.ai/sao/DataStoreType"]
        remarks = node["remarks"]["en"]
        self.assertEqual(remarks.count("<li>"), 14)
        self.assertEqual(remarks.count("<code>document_db</code>"), 1)
        self.assertEqual(remarks.count("<code>flat_file</code>"), 1)

    def test_every_enum_glossary_matches_turtle_once(self):
        class Items(HTMLParser):
            def __init__(self):
                super().__init__()
                self.items = []
            def handle_starttag(self, tag, attrs):
                if tag == "li":
                    self.items.append("")
            def handle_data(self, data):
                if self.items:
                    self.items[-1] += data

        checked = 0
        for entry in catalog().values():
            for product in entry["products"]:
                if not product.endswith("vocabulary"):
                    continue
                graph = assemble(ROOT / entry["source"] / "manifests" / (product + ".json"))
                for datatype in graph.subjects(RDF.type, RDFS.Datatype):
                    values = {value for predicate, value in graph.predicate_objects(datatype)
                              if str(predicate).endswith("/permissibleValue")}
                    if not values:
                        continue
                    with self.subTest(datatype=str(datatype)):
                        remarks = self.classes[str(datatype)]["remarks"]["en"]
                        glossary = remarks.split("<h3>Allowed values</h3><ul>", 1)[1].split("</ul>", 1)[0]
                        parser = Items()
                        parser.feed(glossary)
                        expected = []
                        for value in values:
                            label = str(graph.value(value, RDF.value))
                            description = graph.value(value, RDFS.comment)
                            expected.append(label + (": " + str(description) if description else ""))
                        self.assertEqual(Counter(parser.items), Counter(expected))
                    checked += 1
        self.assertGreater(checked, 0)

    def test_source_manifest_hashes_and_portability(self):
        expected = set()
        for entry in catalog().values():
            for name in entry["products"]:
                manifest = ROOT / entry["source"] / "manifests" / (name + ".json")
                expected.update(str(Path(entry["source"]) / p) for p in json.loads(manifest.read_text())["files"])
        self.assertEqual({item["path"] for item in self.metadata["inputs"]}, expected)
        for item in self.metadata["inputs"]:
            self.assertFalse(Path(item["path"]).is_absolute())
            self.assertEqual(item["sha256"], hashlib.sha256((ROOT / item["path"]).read_bytes()).hexdigest())
        self.assertNotIn("built_at", self.metadata)

    def test_projection_is_reproducible(self):
        payload, metadata = project()
        self.assertEqual(json.dumps(payload, sort_keys=True), json.dumps(self.payload, sort_keys=True))
        self.assertEqual(metadata, self.metadata)

    def test_rdf_anonymous_nodes_serialize_reproducibly(self):
        text = '<urn:shape> <urn:property> [ <urn:path> <urn:field> ] .'
        left = Graph().parse(data=text, format="turtle")
        right = Graph().parse(data=text, format="turtle")
        self.assertEqual(turtle(left), turtle(right))


class EditorialTests(unittest.TestCase):
    def rendered(self, name):
        import tempfile
        from scripts.build_site import prose
        from scripts.catalog import catalog
        with tempfile.TemporaryDirectory() as temporary:
            output = Path(temporary)
            prose(output, {"ontologies": catalog()})
            page = output / name / 'index.html' if name else output / 'index.html'
            self.assertTrue(page.is_file(), f'Missing authored route: {name}')
            return page.read_text()

    def test_exchange_has_responsive_complete_geometry(self):
        import re
        html = self.rendered('ecosystem')
        for layout in ('desktop', 'mobile'):
            match = re.search(r'<svg[^>]*data-exchange-layout="' + layout + r'"[^>]*>(.*?)</svg>', html, re.S)
            self.assertIsNotNone(match, 'Missing responsive ' + layout + ' exchange')
            assert match is not None
            diagram = match.group(1)
            self.assertEqual(re.findall(r'data-story-step="(\d)"', diagram), ['1', '2', '3', '4'])
            for label in ('Analysis tool', 'Shared graph', 'Review tool', 'Sample import report'):
                self.assertIn(label, diagram)
            self.assertNotIn('data-supporting-definitions', diagram)
        css = (ROOT / 'web/styles/editorial.css').read_text()
        self.assertIn('story-travel-horizontal', css)
        self.assertIn('story-travel-vertical', css)
        self.assertIn('[data-exchange-layout="desktop"]', css)
        self.assertIn('[data-exchange-layout="mobile"]', css)

    def test_exchange_status_is_consolidated_and_retained_is_not_truth(self):
        import re
        html = self.rendered('ecosystem')
        from tests.test_site_search import Elements
        self.assertEqual(sum('data-exchange-status' in attrs for _, attrs in Elements(html).nodes), 1)
        self.assertLess(html.index('data-exchange-status'), html.index('data-story="exchange"'))
        for phrase in ('Illustrative exchange—not implemented', 'not a demonstrated integration',
                       'preserved information, not verified truth', 'Illustrative sample import report'):
            self.assertIn(phrase, html)
        caption_match = re.search(r'<figcaption>(.*?)</figcaption>', html, re.S)
        assert caption_match is not None
        caption = caption_match.group(1)
        self.assertNotIn('does not run', caption)
        self.assertNotIn('not evidence', caption)
        self.assertIn('class="story-replay-secondary"', caption)
        self.assertIn('Replay illustration', caption)
        self.assertIn('does not execute the programs', html)
        css = (ROOT / 'web/styles/editorial.css').read_text()
        self.assertRegex(css, r'\.story-replay-secondary[^}]*background:var\(--white\)')

    def test_home_has_one_orientation_before_model_roles_and_search(self):
        html = self.rendered('')
        for redundant in ('First, understand the story.', 'From a callable to a connected story.', 'journey-teaser', 'start-section'):
            self.assertNotIn(redundant, html)
        for anchor in ('start-here', 'journey-title'):
            self.assertIn('<span id="' + anchor + '"></span>', html)
        self.assertIn('href="ecosystem/"', html)
        self.assertLess(html.index('aria-label="Learning path"'), html.index('id="two-ontologies"'))
        self.assertLess(html.index('id="two-ontologies"'), html.index('id="search"'))

    def test_intro_names_distinctions_and_roles_before_identifiers(self):
        import re
        html = self.rendered('introduction')
        distinctions = re.search(r'<dl[^>]*data-story-distinctions[^>]*>(.*?)</dl>', html, re.S)
        self.assertIsNotNone(distinctions)
        assert distinctions is not None
        self.assertLess(html.index('data-story-distinctions'), html.index('aria-label="Introduction chapters"'))
        for label in ('Requirement', 'Code observation', 'Test evidence', 'No behavioral comparison has run'):
            self.assertIn(label, distinctions.group(1))
        for step, role, identity in [('1', 'Withdrawal function', 'Account.withdraw'), ('2', 'Reject an overdraft', 'no-overdraft'), ('3', 'Observed rejection guard', 'modern-behavior')]:
            card_match = re.search(r'<g data-story-step="' + step + r'">(.*?)</g>', html, re.S)
            assert card_match is not None
            card = card_match.group(1)
            self.assertIn(role, card)
            self.assertLess(card.index(role), card.index(identity))

    def test_intro_technical_depth_is_native_optional_and_old_fragments_are_outside(self):
        import re
        html = self.rendered('introduction')
        depth = re.search(r'<details[^>]*data-technical-depth[^>]*>(.*?)</details>', html, re.S)
        self.assertIsNotNone(depth, 'Raw identity and Turtle depth must be optional')
        assert depth is not None
        self.assertNotIn(' open', depth.group(0).split('>')[0])
        self.assertIn('<summary>', depth.group(1))
        for phrase in ('language-turtle', 'RequirementImplementationLink', 'supporting_anchors'):
            self.assertIn(phrase, depth.group(1))
        for fragment in ('the-optional-bridge-connects-identities', 'now-read-the-actual-turtle'):
            self.assertIn('<span id="' + fragment + '"></span>', html[:depth.start()])
            self.assertNotIn('id="' + fragment + '"', depth.group(1))
        self.assertIn('A connection is not a certification', html[:depth.start()])
        self.assertIn('does not execute', html[depth.end():])

    def test_home_merges_connection_into_model_roles(self):
        html = self.rendered('')
        self.assertNotIn('class="connected-section"', html)
        self.assertEqual(html.count('id="grounded"'), 1)
        self.assertLess(html.index('id="grounded"'), html.index('id="search"'))
        self.assertIn('See an example using both ontologies', html)

    def test_preserves_all_original_learning_page_fragments(self):
        from tests.test_site_search import Elements
        old = {
            '': 'understand-softwareconnect-its-evidence start-here journey-title two-ontologies sao systems-abstraction-ontology specspec specification-evidence-ontology grounded downloads',
            'introduction': 'give-software-a-shared-vocabulary structure structure-title structure-map-title structure-map-desc intent intent-title the-optional-bridge-connects-identities evidence evidence-title behavioral-comparison-pending-outcome-not_run use-it use-title',
            'ecosystem': 'shared-meaning-useful-exchange current current-title sao specspec optional-bridge choose-the-layers-you-need exchange exchange-title exchange-map-title exchange-map-desc reuse-before-extending extend-without-redefining map-at-a-bounded-boundary standards-are-research-questions-not-integration-badges governance governance-title sharing-a-vocabulary-never-implies-sharing-customer-data adoption adoption-title',
        }
        for name, identifiers in old.items():
            ids = [a['id'] for _, a in Elements(self.rendered(name)).nodes if 'id' in a]
            for identifier in identifiers.split():
                self.assertEqual(ids.count(identifier), 1, f'{name}#{identifier}')

    def test_model_explorer_label_explains_upstream_name(self):
        from scripts.build_site import search_panel
        for name in ('sao', 'specspec'):
            html = self.rendered(name)
            self.assertIn('Model explorer', html)
            self.assertIn('The RDF Garden', html)
            self.assertNotIn('in Garden</a>', html)
        self.assertIn('Model explorer', search_panel())

    def test_learning_navigation_and_home_orientation(self):
        from tests.test_site_search import Elements
        for name in ('', 'introduction', 'ecosystem', 'sao', 'specspec'):
            html = self.rendered(name)
            root = '../' if name else ''
            for label, route in (('Start here', 'introduction/'), ('Examples', 'guides/examples/ecosystem/README.html'), ('Reference', 'reference/'), ('Contribute', 'guides/CONTRIBUTING.html')):
                self.assertIn(f'href="{root}{route}">{label}</a>', html)
        home = self.rendered('')
        for phrase in ('See how it works', 'Browse the reference', 'Account.withdraw', '150.00', '100.00', 'Understand', 'See an example', 'Try it', 'Look up details'):
            self.assertIn(phrase, home)
        self.assertLess(home.index('Account.withdraw'), home.index('Authored in Turtle'))
        self.assertIn('aria-label="Learning path"', home)

    def test_vendored_tokens_are_pinned_scoped_and_reject_drift(self):
        import shutil
        import tempfile
        from scripts import build_site
        checker = getattr(build_site, 'check_editorial_tokens', None)
        self.assertTrue(callable(checker), 'Build must verify canonical token provenance')
        checker(ROOT)
        with tempfile.TemporaryDirectory() as temporary:
            root = Path(temporary)
            shutil.copytree(ROOT / 'web', root / 'web')
            target = root / 'web/styles/editorial-tokens.css'
            target.write_text(target.read_text().replace('--gold: #ffd83a', '--gold: #123456'))
            with self.assertRaisesRegex(ValueError, 'token'):
                checker(root)
        manifest = json.loads((ROOT / 'web/brand-provenance.json').read_text())
        self.assertEqual(manifest['revision'], 'f13e6e2d89f53495d21e77bbeddd0a0518aacc41')
        self.assertEqual(manifest['upstream_path'], 'dist/tokens.css')
        upstream = (ROOT / manifest['vendored_path']).read_bytes()
        self.assertEqual(hashlib.sha256(upstream).hexdigest(), manifest['sha256'])
        with tempfile.TemporaryDirectory() as temporary:
            root = Path(temporary)
            shutil.copytree(ROOT / 'web', root / 'web')
            (root / manifest['vendored_path']).write_bytes(upstream + b'\n/* drift */')
            with self.assertRaisesRegex(ValueError, 'token'):
                checker(root)

    def test_editorial_design_is_scoped_and_homepage_keeps_reference_access(self):
        home = self.rendered('')
        self.assertIn('href="introduction/"', home)
        self.assertIn('href="ecosystem/"', home)
        for href in ('reference/', 'guides/', 'index.html#search', 'index.html#downloads', 'source/index.html'):
            self.assertIn('href="' + href + '"', home)
        for name in ('introduction', 'ecosystem'):
            html = self.rendered(name)
            self.assertIn('class="landing editorial-page"', html)
            self.assertIn('href="../assets/styles/editorial.css"', html)
            self.assertIn('href="../assets/styles/editorial-tokens.css"', html)
        namespace = self.rendered('sao')
        self.assertNotIn('editorial.css', namespace)
        css_path = ROOT / 'web/styles/editorial.css'
        self.assertTrue(css_path.is_file())
        css = css_path.read_text()
        for token in ('var(--gold)', 'var(--font-condensed)', 'var(--space-8)', 'prefers-reduced-motion', ':focus-visible'):
            self.assertIn(token, css)
        for banned in ('linear-gradient', 'box-shadow', '@import', 'https://'):
            self.assertNotIn(banned, css)

    def test_light_learning_theme_has_readable_footer_and_responsive_orientation(self):
        import re
        css = (ROOT / 'web/styles/editorial.css').read_text()
        self.assertRegex(css, r'\.editorial-page\s*\{[^}]*background:var\(--paper\)')
        self.assertNotIn('.editorial-page .site-footer { --ink:#ffffff', css)
        # Use the shared light footer tokens; a descendant token cannot color a sibling.
        shared = (ROOT / 'web/styles/site.css').read_text()
        for value in ('--ink:#192421', '--paper:#fff', '--muted:#53645e'):
            self.assertIn(value, shared)
        for name in ('', 'introduction', 'ecosystem'):
            self.assertNotIn('data-theme="dark"', self.rendered(name))
        for selector in ('.home-orientation', '.mini-story', '.learning-path'):
            self.assertIn(selector, shared)
        self.assertIn('grid-template-columns:minmax(0,1fr)', shared)
        self.assertIn('color:#236673', css)
        tokens = (ROOT / 'web/styles/editorial-tokens.css').read_text()
        for token in set(re.findall(r'var\((--space-[\w-]+)\)', css)):
            self.assertIn(token + ':', tokens, 'Unresolved spacing collapses the learning layout')

    def test_ecosystem_separates_present_models_from_proposed_exchange(self):
        from scripts.site_search import plain_text
        html = self.rendered('ecosystem')
        text = plain_text(html)
        for phrase in ('Let software tools share understanding', 'Available now', 'Next proof', 'candidate', 'draft',
                       'Analysis tool', 'Shared software-and-evidence graph', 'Review tool', 'Retained', 'Changed', 'Unsupported',
                       'Hypothetical', 'Proposed', 'not implemented', 'Propose an exchange'):
            self.assertIn(phrase, text)
        self.assertNotIn('Versioned profile', text)
        self.assertNotIn('PROV-O', text)
        self.assertIn('data-supporting-definitions', html)
        self.assertIn('data-story="exchange"', html)
        for href in ('../introduction/', '../guides/docs/interoperability-research.html',
                     '../guides/docs/ecosystem-contributing.html',
                     '../guides/CONTRIBUTING.html', '../guides/examples/ecosystem/README.html'):
            self.assertIn('href="' + href + '"', html)
        for section in ('id="current"', 'id="exchange"', 'id="governance"', 'id="adoption"'):
            self.assertIn(section, html)
        self.assertNotIn('<iframe', html)

    def test_relocated_depth_is_reviewed_public_content_only(self):
        import tempfile
        from scripts.build_site import guides
        from scripts.site_publication import source_manifest, validate_source_inputs
        manifest = source_manifest(ROOT)
        for name in ('docs/interoperability-research.md', 'docs/ecosystem-contributing.md'):
            self.assertIn(name, manifest['files'])
        self.assertIn('docs/content-sources.md', manifest['excluded'])
        self.assertNotIn('docs/content-sources.md', manifest['files'])
        validate_source_inputs(ROOT, manifest)
        with tempfile.TemporaryDirectory() as tmp:
            output = Path(tmp)
            guides(output)
            self.assertFalse((output / 'source/docs/content-sources.md').exists())
            self.assertFalse((output / 'guides/docs/content-sources.html').exists())
            research = (output / 'guides/docs/interoperability-research.html').read_text()
            governance = (output / 'guides/docs/ecosystem-contributing.html').read_text()
            for word in ('PROV-O', 'SKOS', 'SSSOM', 'CodeMeta', 'SPDX', 'CycloneDX', 'SARIF', 'SCIP', 'OpenTelemetry', 'LinkML', 'Protégé', 'not implemented adapters'):
                self.assertIn(word, research)
            for word in ('Current', 'Proposed', 'customer data', 'rollback', 'maintainer effort', 'No adoption baseline', 'business hypotheses'):
                self.assertIn(word, governance)

    def test_story_motion_is_wired_progressive_and_bounded(self):
        from tests.test_site_search import Elements
        import subprocess, shutil
        script = ROOT / 'web/assets/story-motion.js'
        self.assertTrue(script.is_file(), 'Missing once-on-entry story controller')
        for name in ('introduction', 'ecosystem'):
            html = self.rendered(name)
            self.assertIn('src="../assets/story-motion.js"', html)
            parser = Elements(html)
            buttons = [a for a in parser.select('button') if 'data-story-replay' in a]
            self.assertEqual(len(buttons), 1)
            self.assertIn('hidden', buttons[0])
            self.assertEqual(buttons[0]['type'], 'button')
            self.assertIn('data-story-step="1"', html)
            self.assertNotIn('is-playing', html)
        css = (ROOT / 'web/styles/editorial.css').read_text()
        self.assertIn('prefers-reduced-motion:reduce', css)
        self.assertIn('animation:none', css)
        self.assertNotIn('infinite', css)
        self.assertIn('animation:none !important', css, 'Reduced-motion must beat the more specific running selectors')
        self.assertIn('.field-guide .story-map svg { min-width:0;', css)
        self.assertIn('story-travel', css)
        if not shutil.which('node'):
            self.skipTest('Node required for controller event regression')
        result = subprocess.run(['node', '-e', r'''
const assert = require('node:assert/strict'), fs = require('node:fs'), vm = require('node:vm');
const script = fs.readFileSync(process.argv[1], 'utf8');
for (const initiallyReduced of [false, true]) {
  const classes = new Set(), listeners = {}, timers = new Map();
  const button = {hidden:true, disabled:false, addEventListener:(type,fn) => listeners[type]=fn};
  const panel = {classList:{add:c=>classes.add(c),remove:c=>classes.delete(c)}, querySelector:()=>button};
  const media = {matches:initiallyReduced, addEventListener:(_,fn)=>media.change=fn};
  let observer, observed = false, unobserved = false, count = 0;
  const context = {document:{querySelectorAll:()=>[panel]}, window:{matchMedia:()=>media},
    setTimeout:(fn,ms)=>{assert.ok(ms<=5000); timers.set(++count,fn); return count;},
    clearTimeout:id=>timers.delete(id),
    IntersectionObserver:class {constructor(fn){observer=fn;} observe(p){assert.equal(p,panel);observed=true;} unobserve(){unobserved=true;}},
    fetch:()=>{throw Error('No network allowed');}};
  vm.runInNewContext(script,context);
  assert.equal(classes.size,0);
  if(initiallyReduced){assert.equal(button.hidden,true);assert.equal(observed,false);continue;}
  assert.equal(button.hidden,false); assert.equal(observed,true);
  observer([{target:panel,isIntersecting:false}]); assert.equal(classes.size,0);
  observer([{target:panel,isIntersecting:true}]); assert.ok(classes.has('is-playing')); assert.equal(unobserved,true);
  const firstCount=count;
  observer([{target:panel,isIntersecting:true}]); assert.equal(count,firstCount);
  for(const fn of [...timers.values()])fn(); timers.clear(); assert.equal(classes.size,0);
  listeners.click(); assert.ok(classes.has('is-playing')); assert.ok(count>firstCount);
  media.matches=true; media.change(); assert.equal(classes.size,0);assert.equal(timers.size,0);assert.equal(button.hidden,true);
}
console.log('Story entry, once-only, replay, bounded completion, reduced-motion change: pass');
''', str(script)], text=True, capture_output=True)
        self.assertEqual(result.returncode, 0, result.stdout + result.stderr)

    def test_quickstart_connects_public_validation_to_withdrawal_without_execution_claim(self):
        guide = (ROOT / 'docs/getting-started.md').read_text()
        self.assertIn('withdrawal-quickstart:start', guide)
        self.assertIn('$SITE_BASE/source/examples/ecosystem/software.ttl', guide)
        self.assertIn('--shacl sao.shacl.ttl software.ttl', guide)
        self.assertIn('only the software identity', guide)
        self.assertIn('Conforms: True', guide)
        # The existing no-checkout block and anchor remain usable.
        self.assertIn('public-quickstart:start', guide)
        self.assertIn('## Run a public example — no checkout required', guide)

    def test_introduction_starts_with_scenario_then_graph_then_turtle(self):
        html = self.rendered('introduction')
        self.assertLess(html.index('150.00'), html.index('<svg'))
        self.assertLess(html.index('<svg'), html.index('language-turtle'))
        for phrase in ('What is in the software', 'What should happen', 'Which statements refer to which software', 'data-story="withdrawal"', 'supporting_anchors', 'modern-behavior', 'modern-guard'):
            self.assertIn(phrase, html)
        for identity in ('structure-map-title', 'structure-map-desc', 'structure-title', 'structure', 'intent', 'intent-title', 'evidence', 'evidence-title', 'use-it', 'use-title', 'give-software-a-shared-vocabulary', 'the-optional-bridge-connects-identities', 'behavioral-comparison-pending-outcome-not_run'):
            self.assertIn(f'id="{identity}"', html)

    def test_intro_follows_exact_synthetic_fixture_without_claiming_execution(self):
        from scripts.site_search import plain_text
        html = self.rendered('introduction')
        text = plain_text(html)
        graph = Graph().parse(ROOT / 'examples/specspec/modernization/graph.ttl')
        from rdflib import URIRef, Namespace
        spec = Namespace('https://ontologies.corestory.ai/specspec/')
        for identity in ('no-overdraft', 'overdraft-criterion', 'legacy-behavior', 'modern-behavior'):
            statement = str(graph.value(URIRef('urn:specspec:demo:' + identity), spec.statement))
            self.assertIn(statement, text)
        for label in ('observed', 'unreviewed', 'proposed', 'not_run', 'supplied', 'normative',
                      'Account.withdraw', 'System', 'Module', 'CallableUnit',
                      'not asserted in this fixture', 'does not execute', 'synthetic'):
            self.assertIn(label, text)
        for href in ('../reference/#sao:CallableUnit', '../guides/docs/sao/README.html',
                     '../guides/examples/ecosystem/README.html', '../ecosystem/'):
            self.assertIn('href="' + href + '"', html)
        self.assertIn('<svg', html)
        from tests.test_site_search import Elements
        figures = Elements(html).select('figure')
        self.assertTrue(figures)
        self.assertTrue(all(figure.get('tabindex') == '0' and figure.get('aria-label') for figure in figures))
        self.assertIn('<desc', html)
        self.assertIn('aria-labelledby=', html)
        self.assertNotIn('<iframe', html)


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