"""smoke_test - import every command + key module; fail loudly on any error.

Standards: Google SRE Workbook Ch. 17 (Shift-Left); ISO/IEC/IEEE 29119-3
5.4 (test basis); Rule 33 (post-deploy verify); Rule 28.
Run immediately after every deployment.
"""
import importlib
from pathlib import Path
from django.core.management.base import BaseCommand
from django.conf import settings

KEY_MODULES = [
    "exams.models",
    "exams.views",
    "exams.urls",
    "exams.student_task_dispatch",
    "exams.kc_firewall",
    "exams.mizan",
    "exams.mizan_algorithm",
    "exams.parsing",
    "exams.services.expert_panel",
    "exams.middleware_parent_ack",
    "exams.middleware_kernel_guard",
]

class Command(BaseCommand):
    help = "Import-check every project module and management command."
    def handle(self, *args, **opts):
        failed = []
        for mod in KEY_MODULES:
            try:
                importlib.import_module(mod)
                self.stdout.write("OK   " + mod)
            except Exception as e:
                failed.append(mod + ": " + type(e).__name__ + ": " + str(e)[:200])
                self.stdout.write(self.style.ERROR("FAIL " + mod + " - " + str(e)[:200]))
        cmd_dir = Path(settings.BASE_DIR) / "exams" / "management" / "commands"
        for f in sorted(cmd_dir.glob("*.py")):
            if f.name.startswith("_"): continue
            name = "exams.management.commands." + f.stem
            try:
                importlib.import_module(name)
                self.stdout.write("OK   cmd " + f.stem)
            except Exception as e:
                failed.append(name + ": " + type(e).__name__ + ": " + str(e)[:200])
                self.stdout.write(self.style.ERROR("FAIL cmd " + f.stem + " - " + str(e)[:200]))
        if failed:
            self.stdout.write(self.style.ERROR("SMOKE_TEST: " + str(len(failed)) + " failures"))
            for f_ in failed: self.stdout.write("  " + f_)
            raise SystemExit(1)
        self.stdout.write(self.style.SUCCESS("SMOKE_TEST: PASS"))
