from __future__ import annotations

import importlib
import sys
from pathlib import Path

import pytest

from iisi_app_core import autoload


def _create_pkg_file(path: Path, content: str = "") -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content, encoding="utf-8")


def test_autoload_imports_all_modules_except_init(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    pkg_root = tmp_path / "samplepkg"
    _create_pkg_file(pkg_root / "__init__.py")
    _create_pkg_file(pkg_root / "a.py")
    _create_pkg_file(pkg_root / "sub" / "__init__.py")
    _create_pkg_file(pkg_root / "sub" / "b.py")

    sys.path.insert(0, str(tmp_path))
    try:
        package = importlib.import_module("samplepkg")
    finally:
        sys.path.remove(str(tmp_path))

    imported: list[str] = []

    def fake_import_module(module_name: str):
        imported.append(module_name)
        return object()

    monkeypatch.setattr(importlib, "import_module", fake_import_module)
    autoload(package)

    assert imported == ["samplepkg.a", "samplepkg.sub.b"]


def test_autoload_rejects_non_package_input() -> None:
    with pytest.raises(TypeError):
        autoload(object())

