#!/usr/bin/env python3
"""Check a WhatsApp click-to-chat QR code or link: decode it, then show the number and the message it carries.

  python3 wa_check.py whatsapp.png
  python3 wa_check.py --link 'https://wa.me/14155550132?text=Hello%20there'

Needs Python 3; reading a PNG also needs opencv: pip install opencv-python-headless
Exit 0: the link has the shape WhatsApp's click-to-chat page describes. Exit 1: it decoded but something looks wrong (listed). Exit 2: nothing to check (missing or empty file, no code found).
It only reads; it opens no link and sends nothing."""
import os, sys
from urllib.parse import urlsplit, parse_qs

def die(msg):
    print(msg, file=sys.stderr)
    sys.exit(2)

def decode_png(path):
    if not os.path.isfile(path):
        die(f"file not found: {path}")
    if os.path.getsize(path) == 0:
        die(f"file is empty: {path}")
    try:
        import cv2
    except ImportError:
        die("reading a PNG needs opencv: pip install opencv-python-headless")
    img = cv2.imread(path)
    if img is None:
        die(f"not an image OpenCV can read: {path}")
    text, _, _ = cv2.QRCodeDetector().detectAndDecode(img)
    if not text:
        text, _, _ = cv2.QRCodeDetectorAruco().detectAndDecode(img)
    if not text:
        die(f"no QR code decoded from {path}")
    return text

def check(link):
    link = link.strip()  # drops a trailing Windows line break
    if not link:
        die("empty link")
    print("link:    ", link)
    problems = []
    u = urlsplit(link)
    if u.scheme.lower() != "https" or u.netloc.lower() != "wa.me":
        problems.append("does not start with https://wa.me/")
    number = u.path[1:] if u.path.startswith("/") else u.path
    if number.endswith("/"):
        number = number[:-1]  # one trailing slash is ignored
    if number:
        print("number:  ", number)
        if not number.isdigit():
            problems.append("the part after wa.me/ is not only digits (a plus, spaces, brackets, dashes or another path are not allowed)")
        elif number.startswith("0"):
            problems.append("the number starts with 0: WhatsApp's page says to omit zeroes; start with the country code")
        elif len(number) < 7:
            problems.append("the number has fewer than 7 digits (7 is the minimum the Koldflux tool accepts)")
        elif len(number) > 15:
            problems.append("the number has more than 15 digits (15 is the E.164 maximum, our reading, not a WhatsApp page statement)")
    else:
        print("number:   (none: the sender picks the contact)")
    q = parse_qs(u.query, keep_blank_values=True)
    if "text" in q:
        print("message: ", q["text"][0])
    else:
        print("message:  (none)")
    for p in problems:
        print("PROBLEM: ", p)
    return 1 if problems else 0

if __name__ == "__main__":
    a = sys.argv[1:]
    if len(a) == 2 and a[0] == "--link":
        sys.exit(check(a[1]))
    if len(a) == 1 and a[0] != "--link":
        sys.exit(check(decode_png(a[0])))
    print(__doc__.strip(), file=sys.stderr)
    sys.exit(2)
