import ast
from pathlib import Path

SRC_ROOT = Path(__file__).resolve().parents[1] / "src" / "config_inspector"


def _module_file(name: str) -> Path:
    return SRC_ROOT / f"{name}.py"


def _internal_import_modules(filepath: Path) -> set[str]:
    """Collect top-level internal module imports from a Python file."""
    tree = ast.parse(filepath.read_text(encoding="utf-8"))
    imports: set[str] = set()
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            for alias in node.names:
                if alias.name.startswith("config_inspector."):
                    imports.add(alias.name.split(".", maxsplit=2)[1])
        elif isinstance(node, ast.ImportFrom):
            if node.module is None:
                continue
            if node.module.startswith("config_inspector."):
                imports.add(node.module.split(".", maxsplit=2)[1])
    return imports


def _internal_import_paths(filepath: Path) -> set[str]:
    """Collect fully-qualified internal imports from a Python file."""
    tree = ast.parse(filepath.read_text(encoding="utf-8"))
    imports: set[str] = set()
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            for alias in node.names:
                if alias.name.startswith("config_inspector."):
                    imports.add(alias.name)
        elif isinstance(node, ast.ImportFrom):
            if node.module is None:
                continue
            if node.module.startswith("config_inspector."):
                imports.add(node.module)
    return imports


def test_updaters_domain_rules_only_depend_on_updaters_domain():
    rules_file = SRC_ROOT / "updaters" / "domain" / "rules.py"
    imports = _internal_import_paths(rules_file)
    assert imports == {"config_inspector.updaters.domain.exceptions"}


def test_file_content_domain_entities_has_no_internal_dependencies():
    entities_file = SRC_ROOT / "file_content" / "domain" / "entities.py"
    assert _internal_import_modules(entities_file) == set()


def test_file_content_application_ports_has_no_internal_dependencies():
    ports_file = SRC_ROOT / "file_content" / "application" / "ports.py"
    imports = _internal_import_modules(ports_file)
    assert imports == {"file_content"}


def test_updaters_domain_exceptions_has_no_internal_dependencies():
    imports = _internal_import_paths(SRC_ROOT / "updaters" / "domain" / "exceptions.py")
    assert imports == set()


def test_registry_domain_entities_has_no_internal_dependencies():
    imports = _internal_import_paths(SRC_ROOT / "registry" / "domain" / "entities.py")
    assert imports == set()


def test_registry_application_service_has_no_infrastructure_dependency():
    imports = _internal_import_modules(SRC_ROOT / "registry" / "application" / "service.py")
    assert "registry" in imports
    assert "services" not in imports
