import io

from GramAddict.core.config import Config


def test_config_help_format_no_crash():
    """
    Test that calling print_help() on the config parser does not crash.
    This prevents bugs where a '%' symbol in help strings causes argparse
    to fail with "ValueError: unsupported format character".
    """
    config = Config()

    # We redirect stdout/stderr so we don't spam the console, but what matters
    # is that print_help() executes without throwing a ValueError.
    from contextlib import redirect_stdout

    f = io.StringIO()
    with redirect_stdout(f):
        config.parser.print_help()

    output = f.getvalue()
    assert len(output) > 0, "print_help() should output help text."
    assert "Wipe all learned navigation" in output, "Expected blank-start help string in output."


def test_parse_args_no_exit_when_config_loaded(monkeypatch):
    """
    Test that if no CLI arguments are provided (sys.argv == ['run.py']),
    but a config file is loaded, parse_args() should NOT print help and exit.
    """
    import sys

    # Simulate running without arguments
    monkeypatch.setattr(sys, "argv", ["run.py"])

    config = Config()

    # Simulate that we successfully loaded a config dictionary (e.g. from config.yml)
    config.config = {"some_setting": "value"}

    help_called = []
    def mock_print_help(*args, **kwargs):
        help_called.append(True)

    monkeypatch.setattr(config.parser, "print_help", mock_print_help)

    # If parse_args() calls exit(0), it will raise SystemExit
    try:
        config.parse_args()
        # If we get here, no exit() was called.
        # Also, print_help should not have been called.
        assert not help_called, "print_help should not have been called"
    except SystemExit:
        import pytest

        pytest.fail("parse_args() should not exit when a config is loaded.")
