"""
Error Knowledge Packs — Domain-specific error-to-pattern mappings.

Place .py files in this directory to extend the detector. Each module
may define EITHER (or both) of two list constants:

1. KNOWLEDGE — REACTIVE matching against error messages (--analyze mode).
   List of ErrorKnowledge entries. Matched via keywords; used by
   `detect_error_patterns.py --analyze "error msg here"`.

2. PROACTIVE_PATTERNS — PROACTIVE scanning of source files (commit-time).
   List of PatternRule entries. Scanned on every codebase run, same as
   the built-in PATTERNS list in detect_error_patterns.py. Use this for
   project-specific anti-patterns (multi-tenant queries, deontology,
   deploy hygiene, etc.) without forking the global script.

Files starting with underscore are skipped.

Example module (e.g., django.py):

    from detect_error_patterns import ErrorKnowledge, PatternRule

    # REACTIVE — matched against incoming error messages
    KNOWLEDGE = [
        ErrorKnowledge(
            id="EK-DJ-001",
            name="Django template variable not found",
            keywords=["variableerror", "template"],
            alt_keywords=[["does not exist", "template"]],
            category="django",
            rules=[
                PatternRule(
                    id="EK-DJ-001-R1",
                    name="Undefined template variable",
                    description="Template references a variable not passed in context.",
                    severity="medium",
                    file_glob="**/*.html",
                    pattern=r"\\{\\{\\s*\\w+\\.\\w+\\s*\\}\\}",
                    fix_hint="Ensure all template variables are passed in the view context dict",
                ),
            ],
        ),
    ]

    # PROACTIVE — scanned on every commit, blocks on high severity
    PROACTIVE_PATTERNS = [
        PatternRule(
            id="EP-PROJ-001",
            name="Direct query without tenant filter",
            description="Multi-tenant projects must filter by user_id.",
            severity="high",
            file_glob="backend/**/*.py",
            pattern=r"db\\.query\\(MyModel\\)\\s*$",
            negative_pattern=r"user_id|require_admin",
            context_lines=8,
            fix_hint="Add `.filter(MyModel.user_id == user.id)`.",
        ),
    ]
"""
import importlib.util
import sys
from pathlib import Path


def load_all():
    """Load all knowledge packs from .py files in this directory.

    Returns a list of ErrorKnowledge entries from all valid modules.
    Skips files starting with underscore.
    """
    entries = []
    pack_dir = Path(__file__).resolve().parent

    for py_file in sorted(pack_dir.glob("*.py")):
        if py_file.name.startswith("_"):
            continue
        try:
            spec = importlib.util.spec_from_file_location(
                f"error_knowledge.{py_file.stem}", py_file
            )
            if spec and spec.loader:
                mod = importlib.util.module_from_spec(spec)
                spec.loader.exec_module(mod)
                pack_knowledge = getattr(mod, "KNOWLEDGE", [])
                entries.extend(pack_knowledge)
        except Exception as exc:
            print(f"Warning: Failed to load knowledge pack {py_file.name}: {exc}",
                  file=sys.stderr)

    return entries
