"""Tests for CLI argument parser construction and parsing."""

import pytest

from data_exchange_agent.__version__ import __version__
from data_exchange_agent.cli.argument_parser import create_argument_parser
from data_exchange_agent.constants.config_defaults import (
    DEFAULT__SERVER__HOST,
    DEFAULT__SERVER__PORT,
)


def test_version_flag_exits_zero(capsys):
    """``--version`` prints the package version and exits with code 0."""
    parser = create_argument_parser()
    with pytest.raises(SystemExit) as exc_info:
        parser.parse_args(["--version"])
    assert exc_info.value.code == 0
    out = capsys.readouterr().out
    assert __version__ in out


def test_test_subcommand_with_config_short():
    """The ``test`` subcommand accepts ``-c`` for the config path."""
    parser = create_argument_parser()
    args = parser.parse_args(["test", "-c", "/path/to/config.toml"])
    assert args.command == "test"
    assert args.config == "/path/to/config.toml"


def test_test_subcommand_with_config_long():
    """The ``test`` subcommand accepts ``--config`` for the config path."""
    parser = create_argument_parser()
    args = parser.parse_args(["test", "--config", "/other.toml"])
    assert args.command == "test"
    assert args.config == "/other.toml"


def test_run_subcommand_flags():
    """The ``run`` subparser exposes server and task-related flags."""
    parser = create_argument_parser()
    args = parser.parse_args(
        [
            "run",
            "-c",
            "/cfg.toml",
            "--no-server",
            "-w",
            "8",
            "-i",
            "30",
            "--host",
            "0.0.0.0",
            "-p",
            "9000",
            "-d",
        ]
    )
    assert args.command == "run"
    assert args.config == "/cfg.toml"
    assert args.no_server is True
    assert args.max_parallel_tasks == 8
    assert args.interval == 30
    assert args.host == "0.0.0.0"
    assert args.port == 9000
    assert args.debug is True


def test_back_compat_run_flags_on_main_parser_without_run_subcommand():
    """Run-related flags work on the root parser without an explicit ``run`` command."""
    parser = create_argument_parser()
    args = parser.parse_args(["-w", "3", "-p", "8080", "--host", "127.0.0.1"])
    assert args.command is None
    assert args.max_parallel_tasks == 3
    assert args.port == 8080
    assert args.host == "127.0.0.1"


def test_main_parser_run_defaults():
    """Host and port default to configured constants when omitted."""
    parser = create_argument_parser()
    args = parser.parse_args([])
    assert args.host == DEFAULT__SERVER__HOST
    assert args.port == DEFAULT__SERVER__PORT
