from pathlib import Path
import os
import subprocess
import sys
import ast

root = Path(__file__).resolve().parent.parent
groups = {
    "php": ["app", "bootstrap", "config", "database", "routes", "docker", "ci", "tests"],
    "js": ["resources/js", "tests/js", "ci"],
    "sh": ["docker", "ci", "ops"],
}
counts = {}
excluded = {"cache", "credentials", ".credentials", "secrets", "monitoring-secrets", ".secrets", ".aws", ".ssh", ".git", "vendor", "node_modules"}


def sources(folder, extension):
    for directory, children, names in os.walk(root / folder):
        if folder == "ops" and Path(directory) == root / "ops":
            children[:] = [name for name in children if name != "workspace"]
        children[:] = [name for name in children if name not in excluded and not name.startswith((".env", ".post76-secrets-")) and not (Path(directory) / name).is_symlink()]
        for name in names:
            path = Path(directory) / name
            if name.endswith("." + extension) and not name.startswith(".env") and not path.is_symlink():
                yield path


for extension, folders in groups.items():
    files = sorted({file for folder in folders for file in sources(folder, extension)})
    if extension == "js":
        files += sorted((root / "ci").glob("*.mjs")) + [root / "vite.config.js"]
    for file in files:
        command = {"php": ["php", "-l"], "js": ["node", "--check"], "sh": ["sh", "-n"]}[extension]
        result = subprocess.run(command + [str(file)], cwd=root, capture_output=True, text=True)
        if result.returncode:
            sys.stderr.write(result.stdout + result.stderr)
            sys.exit(result.returncode)
    counts[extension] = len(files)
print("Syntax checks passed: " + ", ".join(f"{count} {extension} files" for extension, count in counts.items()))
for folder in ["ci", "ops", "docker/monitoring"]:
    for file in sources(folder, "py"):
        ast.parse(file.read_text(), filename=str(file))
print("Python syntax checks passed")
