"""BandWove NFC wristband sizing examples, v1.0. Python 3, standard library."""
import csv
from pathlib import Path

CAPACITY = {"NTAG213": 144, "NTAG215": 496, "NTAG216": 872}
contact = "\r\n".join([
    "BEGIN:VCARD", "VERSION:4.0", "FN:Alex Rivera", "ORG:Example Events",
    "TITLE:Exhibitor Services Manager", "EMAIL:alex@example.org",
    "TEL;VALUE=uri:tel:+1-202-555-0100", "URL:https://example.org/exhibitors/alex",
    "END:VCARD", ""
])
schedule = "\n".join([
    "Weekend workshop guide | Hall B",
    "Friday 16:00 | Badge pickup at the west entrance. Bring your booking reference.",
    "Friday 17:30 | Meet the workshop hosts at the welcome desk inside Hall B.",
    "Saturday 09:00 | Doors open. Check your session number at the information desk.",
    "Saturday 10:00 | Print workshop, Studio A. Aprons and materials are provided.",
    "Saturday 13:00 | Poster workshop, Studio B. Bring your sketch from the morning.",
    "Sunday 10:00 | Portfolio review in Hall B. Sign up at the welcome desk.",
    "Sunday 15:30 | Collect your finished work from Studio A before the hall closes."
])
examples = [
    ("Schedule link", "URI", "https://example.org/schedule"),
    ("Exhibitor contact link", "URI", "https://example.org/exhibitors/alex"),
    ("Exhibitor contact stored on band", "vCard", contact),
    ("Workshop guide stored on band", "Text", schedule),
]

def encode(kind, source):
    raw = source.encode("utf-8")
    if kind == "URI":
        assert raw.startswith(b"https://")
        return 1, b"U", b"\x04" + raw[8:]
    if kind == "vCard":
        return 2, b"text/vcard", raw
    return 1, b"T", b"\x02en" + raw

def rows():
    for name, kind, source in examples:
        tnf, record_type, payload = encode(kind, source)
        short = len(payload) < 256
        flags = 0xc0 | (0x10 if short else 0) | tnf
        payload_length = len(payload).to_bytes(1 if short else 4, "big")
        message = bytes([flags, len(record_type)]) + payload_length + record_type + payload
        tlv_length = bytes([len(message)]) if len(message) < 255 else b"\xff" + len(message).to_bytes(2, "big")
        stored = b"\x03" + tlv_length + message + b"\xfe"
        chip = next((c for c, size in CAPACITY.items() if len(stored) <= size), "exceeds layout")
        yield [name, kind, source, len(source.encode("utf-8")), len(payload), len(message), len(stored), chip, stored.hex()]

if __name__ == "__main__":
    path = Path(__file__).with_name("wristband-ndef-examples.csv")
    with path.open("w", encoding="utf-8", newline="") as file:
        writer = csv.writer(file)
        writer.writerow(["scenario", "record_kind", "exact_input", "input_bytes", "payload_bytes",
                         "ndef_message_bytes", "type2_bytes_with_terminator", "smallest_of_three", "type2_hex"])
        for row in rows():
            writer.writerow(row)
            print(row[0], row[3:8])
