import importlib.metadata

import pytest


def _has_dist(name: str) -> bool:
    try:
        importlib.metadata.version(name)
    except importlib.metadata.PackageNotFoundError:
        return False
    return True


def _can_import_old_gjalla() -> bool:
    """Check if the OLD gjalla module (not gjalla_precommit) can be imported."""
    try:
        # The old gjalla package had a module named 'gjalla' directly
        # The new package uses 'gjalla_precommit' as the module name
        import gjalla  # noqa: F401
        # If we get here and it's the old package, it will have 'organize' command
        return hasattr(gjalla, '__file__') and 'gjalla_precommit' not in str(gjalla.__file__)
    except (ImportError, ModuleNotFoundError):
        return False


@pytest.mark.skipif(not _can_import_old_gjalla(), reason="old gjalla package not installed")
def test_old_gjalla_shows_deprecation_warning():
    import warnings

    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter("always")
        __import__("gjalla")
    assert any("renamed" in str(w.message).lower() for w in caught)


@pytest.mark.skipif(not _has_dist("gjalla-docs"), reason="gjalla-docs package not installed")
def test_gjalla_docs_installs_correctly():
    __import__("gjalla_docs")


@pytest.mark.skipif(not _has_dist("gjalla-docs"), reason="gjalla-docs package not installed")
def test_gjalla_docs_organize_works():
    from click.testing import CliRunner

    cli = __import__("gjalla_docs.cli", fromlist=["main"]).main
    result = CliRunner().invoke(cli, ["organize", "--help"])
    assert result.exit_code == 0


@pytest.mark.skipif(not _has_dist("gjalla"), reason="gjalla package not installed")
def test_new_gjalla_installs_correctly():
    cli = __import__("gjalla_precommit.cli", fromlist=["main"]).main
    result = __import__("click.testing", fromlist=["CliRunner"]).CliRunner().invoke(cli, ["--help"])
    assert result.exit_code == 0


@pytest.mark.skipif(not (_has_dist("gjalla") and _has_dist("gjalla-docs")), reason="packages not installed")
def test_no_command_conflict():
    gjalla_cli = __import__("gjalla_precommit.cli", fromlist=["main"]).main
    docs_cli = __import__("gjalla_docs.cli", fromlist=["main"]).main
    assert gjalla_cli is not docs_cli
