#!/usr/bin/env python3
"""
Impinj R700 IoT Device Interface - POC usando driver impinj_iot
===============================================================

Uso:
    python poc.py --host 192.168.17.195
    python poc.py --host 192.168.17.195 --power 30.0 --antennas 1,2
"""

import argparse
import signal
import sys
import time
from datetime import datetime

from impinj_iot import ImpinjIot, ImpinjIotTagReport, RfMode


def main():
    parser = argparse.ArgumentParser(description="Impinj R700 IoT Driver - POC")
    parser.add_argument("--host", required=True, help="IP o hostname del R700")
    parser.add_argument("--power", type=float, default=30.0, help="Potencia en dBm (default: 30.0)")
    parser.add_argument("--antennas", default="1", help="Puertos de antena separados por coma (default: 1)")
    parser.add_argument("--rf-mode", type=int, default=2, help="RF Mode ID (default: 1004, MaxMiller M4)") # 2, 246
    args = parser.parse_args()

    reader = ImpinjIot()

    tag_count = 0
    unique_epcs = set()

    def on_tag(report: ImpinjIotTagReport):
        nonlocal tag_count
        tag_count += 1
        is_new = report.epc not in unique_epcs
        unique_epcs.add(report.epc)
        timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
        new_marker = " NEW" if is_new else ""
        print(
            f"  [{timestamp}] EPC: {report.epc}  |  "
            f"RSSI: {report.peak_rssi_cdbm} cdBm  |  "
            f"Ant: {report.antenna_port}  |  "
            f"Total: {tag_count}  |  "
            f"Unique: {len(unique_epcs)}{new_marker}"
        )

    # Connect
    print(f"Connecting to {args.host}...")
    if not reader.connect(ip=args.host):
        print("Connection failed")
        sys.exit(1)

    # Show reader info
    info = reader.get_reader_info()
    if info:
        print(f"Reader: {info.model} ({info.serial_number})")
        print(f"Antennas: {info.antenna_count}, Power range: {info.min_tx_power_cdbm/100}-{info.max_tx_power_cdbm/100} dBm")

    # Show supported RF modes
    rf_modes = reader.get_supported_rf_modes()
    if rf_modes:
        print(f"Supported RF modes ({len(rf_modes)}):")
        print(f"  {'ID':>5}  {'Name':<28} {'Mod':<5} {'BLF':>6} {'Tari':>7} {'DR':<6}")
        print(f"  {'─'*5}  {'─'*28} {'─'*5} {'─'*6} {'─'*7} {'─'*6}")
        for mode_id, mode_info in sorted(rf_modes.items()):
            blf = f"{mode_info['blf_khz']}k" if mode_info['blf_khz'] else "auto"
            tari = f"{mode_info['tari_us']}us" if mode_info['tari_us'] else "auto"
            try:
                name = RfMode(mode_id).name
            except ValueError:
                name = f"Unknown({mode_id})"
            print(f"  {mode_id:>5}  {name:<28} {mode_info['modulation']:<5} {blf:>6} {tari:>7} {mode_info['dr']:<6}")

    # Configure
    reader.set_tx_power(args.power)
    reader.set_rf_mode(RfMode(args.rf_mode))

    antenna_ports = [int(a.strip()) for a in args.antennas.split(",")]
    antenna_config = [False] * (info.antenna_count if info else 4)
    for port in antenna_ports:
        if 1 <= port <= len(antenna_config):
            antenna_config[port - 1] = True
    reader.set_antenna_config(antenna_config)

    reader.set_notification_callback(on_tag)

    # Start
    print(f"Starting inventory (rfMode={args.rf_mode}, power={reader.get_tx_power()} dBm)...")
    if not reader.start():
        print("Failed to start inventory")
        reader.disconnect()
        sys.exit(1)

    print("-" * 65)
    print("  Reading tags... Press Ctrl+C to stop")
    print("-" * 65)

    def signal_handler(sig, frame):
        print("\nStopping...")
        reader.stop()
        print(f"\nTotal reads: {tag_count}, Unique EPCs: {len(unique_epcs)}")
        for epc in sorted(unique_epcs):
            print(f"  {epc}")
        reader.disconnect()
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)

    while True:
        time.sleep(0.5)


if __name__ == "__main__":
    main()
