"""
HelaPOS Direct ADB Notification Listener for BlueStacks
Monitors HelaPOS transactions inside BlueStacks without installing any extra forwarder app!
When a payment notification arrives, it immediately triggers HTG Digital auto-fulfillment.
"""

import os
import re
import time
import subprocess
import requests

ADB_PATH = r"C:\Program Files\BlueStacks_nxt\HD-Adb.exe"
WEB_SERVER_URL = "http://127.0.0.1:5000/api/payment/sms_webhook"


def get_active_device():
    """Finds active BlueStacks ADB device instance."""
    try:
        res = subprocess.run([ADB_PATH, "devices"], capture_output=True, text=True)
        lines = res.stdout.strip().split("\n")[1:]
        for line in lines:
            parts = line.split()
            if len(parts) >= 2 and parts[1] == "device":
                return parts[0]
    except Exception as e:
        print(f"⚠️ ADB Error: {e}")
    return None


def run_adb_command(device: str, cmd_args: list) -> str:
    """Executes ADB shell command on the device."""
    full_cmd = [ADB_PATH, "-s", device, "shell"] + cmd_args
    try:
        res = subprocess.run(full_cmd, capture_output=True, text=True, timeout=10)
        return res.stdout
    except Exception as e:
        return ""


def monitor_notifications():
    print("=" * 60)
    print("🤖 HelaPOS BlueStacks ADB Auto-Listener Initializing...")
    print("=" * 60)

    device = get_active_device()
    if not device:
        print("⏳ Waiting for BlueStacks to open... (Make sure BlueStacks is running)")
        while not device:
            time.sleep(3)
            device = get_active_device()

    print(f"✅ Connected to BlueStacks Instance: {device}")
    print("👀 Listening for incoming HelaPOS LankaQR Payment Notifications...\n")

    seen_notifications = set()

    while True:
        try:
            device = get_active_device()
            if not device:
                time.sleep(3)
                continue

            # Dump active Android notifications
            output = run_adb_command(device, ["dumpsys", "notification", "--noredact"])
            if not output:
                time.sleep(2)
                continue

            # Look for Seylan / HelaPOS notifications
            # Lines matching notification text
            lines = output.split("\n")
            for line in lines:
                if any(k in line.lower() for k in ["helapos", "seylan", "lankaqr", "credited", "payment of", "received"]):
                    line_clean = line.strip()
                    # Check if already processed
                    notif_hash = hash(line_clean)
                    if notif_hash in seen_notifications:
                        continue

                    # Extract Amount
                    amt_match = re.search(r"(?:LKR|Rs\.?|Payment of|credited\s+with|Amount:?)\s*([\d,]+\.?\d*)", line_clean, re.IGNORECASE)
                    if not amt_match:
                        amt_match = re.search(r"([\d,]+\.\d{2})", line_clean)

                    if amt_match:
                        seen_notifications.add(notif_hash)
                        print(f"⚡ [NEW NOTIFICATION DETECTED]: {line_clean}")
                        
                        # Post to server webhook
                        try:
                            payload = {"sender": "BlueStacks_HelaPOS", "message": line_clean}
                            r = requests.post(WEB_SERVER_URL, json=payload, timeout=8)
                            print(f"🚀 Auto-Fulfillment Triggered: {r.json()}\n")
                        except Exception as ex:
                            print(f"❌ Failed to notify Web Store: {ex}")

        except Exception as e:
            time.sleep(2)

        time.sleep(2)


if __name__ == "__main__":
    monitor_notifications()
