"""
Exercise 2: sys.modules caching and one-time execution (real dynamic import)

STEP 1: Implement `write_module(tmp_dir, module_name, source)` — write
        `source` to a file named f"{module_name}.py" inside `tmp_dir`
        (use pathlib or plain open()).

STEP 2: Implement `import_twice(tmp_dir, module_name)`:
          - insert `tmp_dir` at the FRONT of `sys.path` if it isn't
            already there (so the module can be found)
          - import the module by name using `importlib.import_module`
          - import it again, by name, the same way
          - return the tuple (first_import_result, second_import_result)

The self-check writes a real temporary module to disk whose top-level
code increments a shared counter every time its body actually runs, then
imports it twice via `import_twice` and proves: (a) both imports return
the exact same module object (identity, via `sys.modules` caching), and
(b) the module's top-level code only ran ONCE despite two imports.
"""

import importlib
import sys
from pathlib import Path


def write_module(tmp_dir, module_name, source):
    # TODO: write `source` to Path(tmp_dir) / f"{module_name}.py"
    pass


def import_twice(tmp_dir, module_name):
    # TODO:
    #   if tmp_dir not in sys.path: sys.path.insert(0, tmp_dir)
    #   first = importlib.import_module(module_name)
    #   second = importlib.import_module(module_name)
    #   return (first, second)
    pass


# --- self-check: do not modify below this line ---
import tempfile
import builtins

checks = []

builtins._modpkg_exercise_count = 0  # shared counter the temp module increments on load

MODULE_SOURCE = (
    "import builtins\n"
    "builtins._modpkg_exercise_count += 1\n"
    "VALUE = 42\n"
)

with tempfile.TemporaryDirectory() as tmp_dir:
    write_module(tmp_dir, "modpkg_exercise_temp", MODULE_SOURCE)
    sys.modules.pop("modpkg_exercise_temp", None)  # ensure a clean slate for this run

    first_mod, second_mod = import_twice(tmp_dir, "modpkg_exercise_temp")

    checks.append(("both imports return the identical module object (sys.modules cache)",
                    first_mod is second_mod, True))
    checks.append(("the imported module exposes VALUE correctly",
                    getattr(first_mod, "VALUE", None), 42))
    checks.append(("the module's top-level code ran exactly ONCE, not twice",
                    builtins._modpkg_exercise_count, 1))

    sys.modules.pop("modpkg_exercise_temp", None)  # cleanup
    if tmp_dir in sys.path:
        sys.path.remove(tmp_dir)

del builtins._modpkg_exercise_count

passed = 0
for label, actual, expected in checks:
    ok = actual == expected
    passed += ok
    print(f"{'PASS' if ok else 'FAIL'}: {label} (got {actual!r}, expected {expected!r})")

print("PASS" if passed == len(checks) else "FAIL")
