import socket
import os
from crccheck.crc import CrcArc

def clear_screen():
    os.system("cls" if os.name == "nt" else "clear")

def send_tcp_message(host, port, message: bytes):
    try:
        with socket.create_connection((host, port), timeout=10) as sock:
            print(f"📤 Sending: {message}")
            sock.sendall(message)
            response = sock.recv(1024)
            print(f"📥 Received: {response}")
    except Exception as e:
        print(f"❌ Error sending message: {e}")

def build_sia_dcs_message():
    client_id = input("Enter Client ID (e.g. 1234): ").zfill(4)
    code = input("Enter Event Code (e.g. OP, RP, BA): ").upper()
    zone = input("Enter Zone (e.g. 01): ").zfill(2)
    image_url = input("Optional Image URL (or leave blank): ")

    body = f'"SIA-DCS"0001L0#{client_id}[{client_id}|Nri1/{code}{zone}]'
    if image_url:
        body += f'[V{image_url}]'

    body_bytes = body.encode("ascii")
    crc = CrcArc.calc(body_bytes)
    length = f"{len(body_bytes):04X}"  # Hex, 4-digit, upper-case

    full_message = f"\n{crc:04X}{length}{body}\r".encode("ascii")
    return full_message

def build_adm_cid_message():
    seq = input("Enter sequence number (e.g. 0000): ").zfill(4)
    line = input("Enter line number (e.g. 3): ").zfill(1)
    account = input("Enter account number (e.g. 1234): ").zfill(4)
    code = input("Enter event code (e.g. 1131): ").zfill(4)
    area = input("Enter area/partition (e.g. 01): ").zfill(2)
    zone = input("Enter zone/user (e.g. 015): ").zfill(3)
    image_url = input("Optional Image URL (or leave blank): ")

    body = f'"ADM-CID"{seq}L{line}#{account}[#{account}|{code} {area} {zone}]'
    if image_url:
        body += f'[V{image_url}]'
    body_bytes = body.encode("ascii")
    crc = CrcArc.calc(body_bytes)
    length = f"{len(body_bytes):04X}"

    full_message = f"\n{crc:04X}{length}{body}\r".encode("ascii")
    return full_message

def main():
    clear_screen()
    print("🚨 Alarm Test Sender")
    host = input("Enter receiver IP (e.g. 127.0.0.1): ")
    port = int(input("Enter port (e.g. 9000): "))

    while True:
        print("\nChoose protocol:")
        print("1. Send SIA-DCS message")
        print("2. Send ADM-CID message")
        print("3. Exit")

        choice = input("Select (1/2/3): ")

        if choice == "1":
            msg = build_sia_dcs_message()
            send_tcp_message(host, port, msg)
        elif choice == "2":
            msg = build_adm_cid_message()
            send_tcp_message(host, port, msg)
        elif choice == "3":
            print("👋 Bye!")
            break
        else:
            print("Invalid choice")

if __name__ == "__main__":
    main()
