"""
Quick B9 Test - Verifica accesso messaggio B9 in modalità simulazione
"""

import __init__
import sys
import logging

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

def quick_test_b9():
    """Test rapido B9 in modalità mock."""
    logging.info("=== B9 Quick Test (Mock Mode) ===\n")
    
    # Import mock
    import GRIFO_M_PBIT_mock as mock
    
    # Create mock interface
    logging.info("1. Creating mock interface...")
    interface = mock.MockGrifo1553Interface()
    logging.info("   ✓ Mock interface created\n")
    
    # Test B9 message counter
    logging.info("2. Testing B9 message counter...")
    try:
        count = interface.getSingleMessageReceivedSz("B9")
        logging.info(f"   ✓ B9 message counter: {count}\n")
    except Exception as e:
        logging.error(f"   ✗ Error getting B9 counter: {e}\n")
        return False
    
    # Test B9 field access
    logging.info("3. Testing B9 field values...")
    test_fields = [
        ('b9_t_num', 'Number of targets'),
        ('b9_t1_rng', 'Target 1 range'),
        ('b9_w12', 'Word 12'),
        ('b9_t1_az', 'Target 1 azimuth'),
    ]
    
    for field, desc in test_fields:
        try:
            value = interface.getMessageFieldValue("B9", field)
            logging.info(f"   ✓ {field:12s} = {value:>6} ({desc})")
        except Exception as e:
            logging.error(f"   ✗ {field:12s} - Error: {e}")
            return False
    
    logging.info("\n4. Simulating target detection...")
    # Initialize field values (simula un run)
    interface._initialize_field_values()
    
    # Read again
    t_num = interface.getMessageFieldValue("B9", "b9_t_num")
    t_rng = interface.getMessageFieldValue("B9", "b9_t1_rng")
    
    logging.info(f"   After initialization:")
    logging.info(f"     - Targets detected: {t_num}")
    logging.info(f"     - Target 1 range:   {t_rng}")
    
    if t_num > 0:
        logging.info(f"   ✓ Target simulated successfully!\n")
    else:
        logging.info(f"   ⚠ No target simulated (depends on run pattern)\n")
    
    logging.info("=== TEST PASSED ===")
    logging.info("B9 message is fully accessible in mock mode!")
    logging.info("\nNext step: Integrate tgt_gen() function with real hardware test")
    return True

if __name__ == '__main__':
    try:
        success = quick_test_b9()
        sys.exit(0 if success else 1)
    except Exception as e:
        logging.error(f"\n=== TEST FAILED ===")
        logging.error(f"Exception: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
