import re
import subprocess
import sys
import tempfile
from pathlib import Path

html_path = Path(r"c:\Projects\DSCons\app\static\bim\index.html")
content = html_path.read_text(encoding="utf-8")

# Extract all inline <script> tags (without src attribute, or containing code)
# Match <script ...> ... </script>
pattern = re.compile(r"<script(?:\s+[^>]*)?>(.*?)</script>", re.DOTALL | re.IGNORECASE)

matches = pattern.findall(content)
print(f"Found {len(matches)} script tags in {html_path}")

all_valid = True
for idx, script_code in enumerate(matches, 1):
    stripped = script_code.strip()
    if not stripped:
        print(f"Script {idx}: empty / external only, skipping.")
        continue
    
    print(f"Script {idx}: length = {len(stripped)} chars, checking syntax with Node.js...")
    with tempfile.NamedTemporaryFile("w", suffix=".js", encoding="utf-8", delete=False) as f:
        f.write(stripped)
        temp_js = f.name
    
    try:
        proc = subprocess.run(["node", "--check", temp_js], capture_output=True, text=True, check=False)
        if proc.returncode == 0:
            print(f"  -> Script {idx}: SYNTAX OK")
        else:
            print(f"  -> Script {idx}: SYNTAX ERROR:\n{proc.stderr}")
            all_valid = False
    finally:
        Path(temp_js).unlink(missing_ok=True)

if all_valid:
    print("\nALL INLINE SCRIPTS PASSED SYNTAX CHECK!")
    sys.exit(0)
else:
    print("\nSYNTAX ERRORS DETECTED!")
    sys.exit(1)
