"""
AgomTradePro SDK Connection Test Script

Tests the SDK's basic connection and functionality.
This script verifies that the SDK can connect to the AgomTradePro API
and perform basic operations.

Usage:
    python test_sdk_connection.py

Requirements:
    - Django server running on http://localhost:8000
    - SDK installed in development mode
"""

import os
import sys
from pathlib import Path

import pytest

# Add project root to Python path
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

# Set environment variables for testing
os.environ["AGOMTRADEPRO_BASE_URL"] = "http://localhost:8000"
os.environ.setdefault("AGOMTRADEPRO_API_TOKEN", "test-token")


@pytest.fixture(scope="module", autouse=True)
def require_acceptance_server() -> None:
    """Skip acceptance SDK tests when the local target server is unavailable."""
    try:
        import requests

        response = requests.get("http://localhost:8000/api/", timeout=3)
        response.raise_for_status()
    except Exception as exc:
        pytest.skip(f"Acceptance SDK tests require a live server at http://localhost:8000: {exc}")


def print_section(title: str) -> None:
    """Print a formatted section header"""
    print("\n" + "=" * 60)
    print(f"  {title}")
    print("=" * 60)


def print_test(name: str) -> None:
    """Print a test name"""
    print(f"\n[{name}]")


def print_success(message: str) -> None:
    """Print a success message"""
    print(f"  OK: {message}")


def print_error(message: str) -> None:
    """Print an error message"""
    print(f"  FAIL: {message}", file=sys.stderr)


def print_info(message: str) -> None:
    """Print an info message"""
    print(f"  INFO: {message}")


def _assert_or_skip_endpoint_error(test_name: str, error: Exception) -> None:
    """For acceptance tests, skip when endpoint/data is unavailable in current env."""
    error_text = str(error)
    if (
        "Connection refused" in error_text
        or "Failed to establish a new connection" in error_text
        or "Max retries exceeded" in error_text
        or "actively refused" in error_text
        or "[404]" in error_text
        or "Resource not found" in error_text
        or "[401]" in error_text
        or "[403]" in error_text
        or "Authentication failed" in error_text
    ):
        pytest.skip(f"{test_name} skipped: API endpoint/data not available in current environment ({error_text})")
    raise AssertionError(f"Failed in {test_name}: {error}")


def test_import_sdk() -> None:
    """Test 1: Import SDK"""
    print_test("Test 1: Import SDK")
    try:
        from sdk.agomtradepro import AgomTradeProClient  # noqa: F401
        print_success("SDK imported successfully")
    except ImportError as e:
        raise AssertionError(f"Failed to import SDK: {e}. " "Make sure the SDK is installed: pip install -e sdk/") from e


def test_create_client() -> None:
    """Test 2: Create Client"""
    print_test("Test 2: Create Client")
    try:
        from sdk.agomtradepro import AgomTradeProClient

        client = AgomTradeProClient()
        print_success("Client created successfully")
        print_info(f"Base URL: {client._config.base_url}")
    except Exception as e:
        raise AssertionError(f"Failed to create client: {e}") from e


def test_get_current_regime() -> None:
    """Test 3: Get Current Regime"""
    print_test("Test 3: Get Current Regime")
    try:
        from sdk.agomtradepro import AgomTradeProClient

        client = AgomTradeProClient()
        regime = client.regime.get_current()

        print_success(f"Current regime: {regime.dominant_regime}")
        print_info(f"Growth level: {regime.growth_level}")
        print_info(f"Inflation level: {regime.inflation_level}")
        print_info(f"Observed at: {regime.observed_at}")
    except Exception as e:
        _assert_or_skip_endpoint_error("get_current_regime", e)


def test_get_policy_status() -> None:
    """Test 4: Get Policy Status"""
    print_test("Test 4: Get Policy Status")
    try:
        from sdk.agomtradepro import AgomTradeProClient

        client = AgomTradeProClient()
        status = client.policy.get_status()

        print_success(f"Current gear: {status.current_gear}")
        print_info(f"Observed at: {status.observed_at}")
        if status.recent_events:
            print_info(f"Recent events: {len(status.recent_events)}")
    except Exception as e:
        _assert_or_skip_endpoint_error("get_policy_status", e)


def test_list_data_center_indicators() -> None:
    """Test 5: List Data Center Indicators"""
    print_test("Test 5: List Data Center Indicators")
    try:
        from sdk.agomtradepro import AgomTradeProClient

        client = AgomTradeProClient()
        indicators = client.data_center.list_indicators()

        print_success(f"Found {len(indicators)} data center indicators")
        if indicators:
            first = indicators[0]
            print_info(f"First indicator: {first.get('code')} - {first.get('name_cn')}")
    except Exception as e:
        _assert_or_skip_endpoint_error("list_data_center_indicators", e)


def test_list_signals() -> None:
    """Test 6: List Investment Signals"""
    print_test("Test 6: List Investment Signals")
    try:
        from sdk.agomtradepro import AgomTradeProClient

        client = AgomTradeProClient()
        signals = client.signal.list()

        print_success(f"Found {len(signals)} investment signals")
        if signals:
            print_info(f"First signal: {signals[0].asset_code} - {signals[0].logic_desc[:50]}...")
    except Exception as e:
        _assert_or_skip_endpoint_error("list_signals", e)


def test_check_signal_eligibility() -> None:
    """Test 7: Check Signal Eligibility"""
    print_test("Test 7: Check Signal Eligibility")
    try:
        from sdk.agomtradepro import AgomTradeProClient

        client = AgomTradeProClient()
        eligibility = client.signal.check_eligibility(
            asset_code="000001.SH",
            logic_desc="Test signal for eligibility check"
        )

        print_success("Eligibility check completed")
        print_info(f"Is eligible: {eligibility.is_eligible}")
        if eligibility.regime_match:
            print_info(f"Regime match: {eligibility.regime_match}")
        if eligibility.policy_match:
            print_info(f"Policy match: {eligibility.policy_match}")
    except Exception as e:
        _assert_or_skip_endpoint_error("check_signal_eligibility", e)


def test_regime_history() -> None:
    """Test 8: Get Regime History"""
    print_test("Test 8: Get Regime History")
    try:
        from sdk.agomtradepro import AgomTradeProClient

        client = AgomTradeProClient()
        history = client.regime.history(limit=5)

        print_success(f"Found {len(history)} regime history records")
        if history:
            print_info(f"Latest: {history[0].dominant_regime} at {history[0].observed_at}")
    except Exception as e:
        _assert_or_skip_endpoint_error("regime_history", e)


def test_list_backtests() -> None:
    """Test 9: List Backtests"""
    print_test("Test 9: List Backtests")
    try:
        from sdk.agomtradepro import AgomTradeProClient

        client = AgomTradeProClient()
        backtests = client.backtest.list()

        print_success(f"Found {len(backtests)} backtests")
    except Exception as e:
        _assert_or_skip_endpoint_error("list_backtests", e)


def test_get_portfolios() -> None:
    """Test 10: Get Portfolios"""
    print_test("Test 10: Get Portfolios")
    try:
        from sdk.agomtradepro import AgomTradeProClient

        client = AgomTradeProClient()
        portfolios = client.account.get_portfolios()

        print_success(f"Found {len(portfolios)} portfolios")
    except Exception as e:
        _assert_or_skip_endpoint_error("get_portfolios", e)


def main() -> int:
    """Run all tests"""
    print_section("AgomTradePro SDK Connection Test")

    # Check if server is running
    print_test("Server Check")
    try:
        import requests
        requests.get("http://localhost:8000/api/", timeout=5)
        print_success("Server is running")
    except Exception as e:
        print_error(f"Cannot connect to server: {e}")
        print_info("Please start the server first: .\\scripts\\start-dev.ps1")
        return 1

    # Run tests
    tests = [
        ("Import SDK", test_import_sdk),
        ("Create Client", test_create_client),
        ("Get Current Regime", test_get_current_regime),
        ("Get Policy Status", test_get_policy_status),
        ("List Data Center Indicators", test_list_data_center_indicators),
        ("List Signals", test_list_signals),
        ("Check Signal Eligibility", test_check_signal_eligibility),
        ("Get Regime History", test_regime_history),
        ("List Backtests", test_list_backtests),
        ("Get Portfolios", test_get_portfolios),
    ]

    results: list[tuple[str, bool]] = []

    for name, test_func in tests:
        try:
            test_func()
            results.append((name, True))
        except AssertionError as e:
            print_error(str(e))
            results.append((name, False))
        except Exception as e:
            print_error(f"Unexpected error: {e}")
            results.append((name, False))

    # Print summary
    print_section("Test Summary")

    passed = sum(1 for _, result in results if result)
    total = len(results)

    for name, result in results:
        status = "PASS" if result else "FAIL"
        symbol = "OK" if result else "X"
        print(f"  [{symbol}] {name}: {status}")

    print()
    print(f"  Total: {passed}/{total} tests passed")

    if passed == total:
        print_success("All tests passed!")
        return 0
    else:
        print_error(f"{total - passed} test(s) failed")
        return 1


if __name__ == "__main__":
    sys.exit(main())
