# ═══════════════════════════════════════════════════════════════════════════════
# coding.sgit.ai — Test__Rendered_Shell
# The highest-value missing check in the estate: the generated shell is currently
# unlintable because it is never rendered outside production. Render every Section__*
# and pipe the result through shellcheck. Skips cleanly when shellcheck is absent.
# Published under CC BY 4.0 — https://coding.sgit.ai/enforce/
# ═══════════════════════════════════════════════════════════════════════════════

import importlib
import re
import shutil
import subprocess
from pathlib  import Path
from unittest import TestCase, skipUnless

USER_DATA      = Path('sg_compute/platforms/ec2/user_data')
MODULE_ROOT    = 'sg_compute.platforms.ec2.user_data'
BREADCRUMB     = re.compile(r'^\s*echo\s+"\[[\w-]+\]', re.M)                     # a bracketed, greppable echo
SECTION_BANNER = re.compile(r'^# ── .+ ─+ *$', re.M)                             # shell banners use ──, not ═══
HAS_SHELLCHECK = shutil.which('shellcheck') is not None


def sections():                                                                  # every Section__* class, by filename
    for path in sorted(USER_DATA.glob('Section__*.py')):
        module = importlib.import_module(f'{MODULE_ROOT}.{path.stem}')
        yield path.stem, getattr(module, path.stem)()


class Test__Rendered_Shell(TestCase):

    @classmethod
    def setUpClass(cls):
        cls.rendered = {name: section.render() for name, section in sections()}
        assert cls.rendered, 'no Section__* classes found — check USER_DATA'

    @skipUnless(HAS_SHELLCHECK, 'shellcheck not installed')
    def test_every_section_passes_shellcheck(self):
        offenders = []
        for name, shell in self.rendered.items():
            result = subprocess.run(['shellcheck', '--shell=bash', '--severity=warning', '-'],
                                    input=shell, capture_output=True, text=True)
            if result.returncode:
                offenders.append(f'{name}:\n{result.stdout.strip()}')
        self.assertEqual([], offenders)

    def test_every_section_opens_with_a_banner(self):
        offenders = [name for name, shell in self.rendered.items()
                     if not SECTION_BANNER.search(shell)]
        self.assertEqual([], offenders)

    def test_every_section_leaves_a_breadcrumb(self):                            # so boot logs stay greppable
        offenders = [name for name, shell in self.rendered.items()
                     if not BREADCRUMB.search(shell)]
        self.assertEqual([], offenders)

    def test_no_unescaped_brace_survived_formatting(self):                       # { means str.format AND brace expansion
        offenders = [name for name, shell in self.rendered.items()
                     if '{' in shell and '${' not in shell]
        self.assertEqual([], offenders)
