"""
Connection test CLI command.

This module provides the 'test' CLI command that verifies database connections
by executing SELECT 1 on all configured source and target connections.
"""

from __future__ import annotations

import argparse
import os

from data_exchange_agent.__version__ import __version__
from data_exchange_agent.config.manager import ConfigManager
from data_exchange_agent.constants.paths import (
    DEFAULT_CONFIGURATION_FILE_PATH,
    get_configuration_file_path,
)
from data_exchange_agent.utils.connection_tester import (
    ConnectionTester,
    print_test_results,
)


def run_connection_test(args: argparse.Namespace) -> int:
    """
    Run the connection test CLI command.

    Tests all configured database connections by executing SELECT 1.

    Args:
        args: Command line arguments (should have 'config' attribute)

    Returns:
        Exit code (0 for success, 1 for failure)

    """
    print(f"\nData Exchange Agent v{__version__}")
    print("=" * 40)

    # Get config path
    config_path = getattr(args, "config", None)
    if config_path:
        config_path = os.path.normpath(config_path)
    else:
        config_path = get_configuration_file_path()

    # Check if config exists
    if not os.path.isfile(config_path):
        print(f"\n  Config not found: {config_path}")
        if not getattr(args, "config", None):
            print(
                f"  Searched: ./configuration.toml, {DEFAULT_CONFIGURATION_FILE_PATH}"
            )
        return 1

    # Load config
    print(f"\nConfig: {config_path}")

    config = ConfigManager()
    try:
        config.load_toml_config(config_path)
    except Exception as e:
        root_cause = e.__cause__ if e.__cause__ else e
        print(f"\n  Config error: {root_cause}")
        return 1

    # Create tester and run tests
    tester = ConnectionTester(config)

    # Test source connections
    print("\nSource Connections:")
    print("-" * 20)
    source_results = tester.test_source_connections()
    if not source_results:
        print("  No source connections configured")
    else:
        print_test_results(source_results, all(r.is_success for r in source_results))

    # Test target connections
    print("\nTarget Connections:")
    print("-" * 20)
    target_results = tester.test_target_connections()
    if not target_results:
        print("  No target connections configured")
    else:
        print_test_results(target_results, all(r.is_success for r in target_results))

    # Summary
    all_results = source_results + target_results
    all_passed = all(r.is_success for r in all_results) if all_results else True

    print("=" * 40)
    if all_passed:
        print("All connections OK\n")
    else:
        print("Some connections failed\n")

    return 0 if all_passed else 1
