"""
Test B9 Message Access
Quick verification script to check if B9 message is accessible via Python interface.
"""

import __init__
import sys
import time
import logging
from leo_grifo_1553 import theGrifo1553

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def test_b9_access():
    """Test if B9 message is accessible and readable."""
    logging.info("=== B9 Message Access Test ===")
    
    try:
        # Get interface
        interface = theGrifo1553.getInterface()
        logging.info("✓ Interface obtained successfully")
        
        # Check if B9 message is defined
        try:
            is_rx = interface.isMessageReadOnly("B9")
            logging.info(f"✓ B9 message is defined, RX={is_rx}")
        except Exception as e:
            logging.error(f"✗ B9 message not defined or not accessible: {e}")
            return False
        
        # Try to get message counter
        try:
            msg_count = interface.getSingleMessageReceivedSz("B9")
            logging.info(f"✓ B9 message counter accessible: {msg_count} messages received")
        except Exception as e:
            logging.error(f"✗ Cannot get B9 message counter: {e}")
            return False
        
        # Try to read key fields (even if count is 0)
        fields_to_test = [
            "b9_t_num",      # Number of targets
            "b9_t1_rng",     # Target 1 range
            "b9_w12",        # Word 12 (timetag)
            "b9_t1_az",      # Target 1 azimuth
            "b9_t2_rng",     # Target 2 range
        ]
        
        logging.info("\nTesting field access:")
        for field in fields_to_test:
            try:
                value = interface.getMessageFieldValue("B9", field)
                logging.info(f"  ✓ {field:15s} = {value}")
            except Exception as e:
                logging.warning(f"  ✗ {field:15s} - Error: {e}")
        
        # If message count > 0, B9 is being transmitted
        if msg_count > 0:
            logging.info(f"\n✓✓ SUCCESS: B9 message is active and receiving data! ({msg_count} messages)")
        else:
            logging.warning(f"\n⚠ B9 message is accessible but no messages received yet (count={msg_count})")
            logging.warning("  This is normal if radar is not transmitting or not in operational mode")
        
        return True
        
    except Exception as e:
        logging.error(f"✗ Test failed with exception: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == '__main__':
    logging.info("Starting B9 access test...")
    logging.info("Note: This test only checks if B9 is accessible, not if radar is transmitting it.\n")
    
    success = test_b9_access()
    
    if success:
        logging.info("\n=== TEST PASSED ===")
        logging.info("B9 message is accessible via Python interface.")
        logging.info("Next step: Verify radar is configured to transmit B9 (operational mode required)")
    else:
        logging.error("\n=== TEST FAILED ===")
        logging.error("B9 message is NOT accessible. Check ICD configuration or bindings.")
    
    sys.exit(0 if success else 1)
