# ═══════════════════════════════════════════════════════════════════════════════
# coding.sgit.ai — Check__Components
# The two JavaScript rules ESLint cannot express: every component directory holds the
# full .js/.html/.css triplet, and every SgComponent subclass declares its own jsUrl.
# Published under CC BY 4.0 — https://coding.sgit.ai/enforce/
# ═══════════════════════════════════════════════════════════════════════════════

import re
import sys
from pathlib import Path

TREE       = Path(sys.argv[1] if len(sys.argv) > 1 else '.').resolve()
TRIPLET    = ('.js', '.html', '.css')
EXTENDS    = re.compile(r'class\s+\w+\s+extends\s+SgComponent\b')
SELF_URL   = re.compile(r'static\s+jsUrl\s*=\s*import\.meta\.url')


def check():
    offenders = []
    for js in sorted(TREE.rglob('*.js')):
        source = js.read_text()
        if not EXTENDS.search(source):                                           # not a component: nothing to check
            continue
        for suffix in TRIPLET:                                                   # the three-file triplet
            sibling = js.with_suffix(suffix)
            if not sibling.exists():
                offenders.append(f'{js}: no sibling {sibling.name}')
        if not SELF_URL.search(source):                                          # self-location is what removes the build step
            offenders.append(f'{js}: extends SgComponent without '
                             f'"static jsUrl = import.meta.url" — it cannot find its own markup')
    return offenders


if __name__ == '__main__':
    problems = check()
    for problem in problems:
        print(f'  ✗ {problem}', file=sys.stderr)
    print(f'check_components: {len(problems)} problem(s)', file=sys.stderr if problems else sys.stdout)
    sys.exit(1 if problems else 0)
