"""
GAP/CONN/NCON/BV-01-C: Non-Connectable Mode.

PTS Action: Select YES when asked "Does the IUT have an ability to send
non-connectable advertising report?"

Configuration (same as GAP/BROB/BCST/BV-01-C):
- Advertising_Type: 0x03 (ADV_NONCONN_IND)
- Flags AD Type (0x01): 0x04 (Not Discoverable, BR/EDR Not Supported)
- Legacy non-connectable advertising packet
"""

import asyncio
import logging
import os

import bumble.device
import bumble.transport
from bumble import hci
from bumble.device import DeviceConfiguration, AdvertisingParameters, AdvertisingEventProperties


async def run_non_connectable():
    """Configure and start non-connectable advertising for GAP/CONN/NCON/BV-01-C."""

    # Transport - adjust as needed for your setup
    transport_str = "serial:/dev/ttyAMA3,1000000,rtscts"

    async with await bumble.transport.open_transport(transport_str) as (hci_source, hci_sink):
        # Device configuration
        device_config = DeviceConfiguration(
            name="PTS-GAP-06B8",
            address=hci.Address("F1:F1:F2:F3:F4:F5"),
        )

        device = bumble.device.Device.from_config_with_hci(
            device_config,
            hci_source,
            hci_sink,
        )
        await device.power_on()

        # Exact advertising data payload (27 bytes) as specified:
        # 0x02, 0x01, 0x04                             - Flags: BR/EDR Not Supported
        # 0x05, 0x03, 0x00, 0x18, 0x01, 0x18           - 16-bit Service UUIDs: 0x1800, 0x1801
        # 0x0D, 0x09, 0x50, 0x54, 0x53, 0x2D, 0x47,    - Complete Local Name: "PTS-GAP-06B8"
        #       0x41, 0x50, 0x2D, 0x30, 0x36, 0x42, 0x38
        # 0x03, 0x19, 0x00, 0x00                       - Appearance: 0x0000
        adv_data = bytes([
            0x02, 0x01, 0x04,                               # Flags: BR/EDR Not Supported
            0x05, 0x03, 0x00, 0x18, 0x01, 0x18,             # 16-bit Service UUIDs
            0x0D, 0x09, 0x50, 0x54, 0x53, 0x2D, 0x47, 0x41, # Local Name: "PTS-GAP-06B8"
            0x50, 0x2D, 0x30, 0x36, 0x42, 0x38,
            0x03, 0x19, 0x00, 0x00                          # Appearance
        ])

        logging.info("Advertising data (%d bytes): %s", len(adv_data), adv_data.hex())

        # Create advertising set with non-connectable parameters (ADV_NONCONN_IND equivalent)
        advertising_set = await device.create_advertising_set(
            advertising_parameters=AdvertisingParameters(
                advertising_event_properties=AdvertisingEventProperties(
                    is_connectable=False,      # Non-connectable (ADV_NONCONN_IND)
                    is_scannable=False,        # Not scannable
                    is_directed=False,
                    is_high_duty_cycle_directed_connectable=False,
                    is_legacy=True,            # Use legacy advertising PDUs
                    is_anonymous=False,
                ),
                primary_advertising_interval_min=0x0800,  # 1.28s
                primary_advertising_interval_max=0x0800,  # 1.28s
                primary_advertising_phy=hci.Phy.LE_1M,
            ),
            advertising_data=adv_data,
            auto_start=True,
        )

        logging.info("Non-connectable advertising started (ADV_NONCONN_IND)")
        logging.info("Advertising set handle: %s", advertising_set.advertising_handle)

        # Keep advertising until interrupted
        logging.info("Press Ctrl+C to stop...")
        try:
            while True:
                await asyncio.sleep(1)
        except asyncio.CancelledError:
            pass
        finally:
            await advertising_set.stop()
            logging.info("Advertising stopped")


if __name__ == "__main__":
    logging.basicConfig(
        level=os.environ.get("LOG_LEVEL", logging.INFO),
        format="%(module)s.py:%(lineno)d %(levelname)s: %(message)s",
    )

    try:
        asyncio.run(run_non_connectable())
    except KeyboardInterrupt:
        logging.info("Interrupted by user")
