# path: modules/quick_start.py
import subprocess
import sys
import os
import platform
import time
from shutil import get_terminal_size

MENU_NAME = "Quick Start"

GOV_SPYWARE_PACKAGES = {
    "com.nsogroup.pega": "Pegasus - NSO Group",
    "com.nsogroup.pegasus": "Pegasus - NSO Group",
    "com.finfisher.mobile": "FinFisher / FinSpy",
    "com.italtel.hermit": "Hermit - RCS Lab",
    "com.cy4root.predator": "Predator - Cytrox",
    "com.hackingteam.htagent": "Hacking Team RCS"
}

def get_adb_path():
    os_map = {"Windows": "windows", "Linux": "linux", "Darwin": "mac"}
    system = platform.system()
    subdir = os_map.get(system)
    if not subdir:
        return None
    root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
    adb_filename = "adb.exe" if system == "Windows" else "adb"
    adb_path = os.path.join(root_dir, "tools", subdir, adb_filename)
    return adb_path if os.path.exists(adb_path) else None

def start_log():
    timestamp = time.strftime("%Y%m%d-%H%M%S")
    log_path = f"spyhunter_log_{timestamp}.txt"
    return open(log_path, "w")

def get_phone_info(adb_path):
    info = {}
    fields = ["ro.product.manufacturer", "ro.product.model", "ro.build.version.release",
              "ro.serialno", "ro.build.version.sdk", "ro.build.display.id"]
    for field in fields:
        result = subprocess.run([adb_path, "shell", "getprop", field], capture_output=True, text=True)
        info[field] = result.stdout.strip()
    return info

def get_installed_packages(adb_path):
    result = subprocess.run([adb_path, "shell", "pm", "list", "packages"], capture_output=True, text=True)
    return [line.replace("package:", "").strip() for line in result.stdout.splitlines()]

def progress_bar(seconds=10):
    width = get_terminal_size((80, 20)).columns - 20
    for i in range(seconds + 1):
        bar = "#" * int((i / seconds) * width)
        sys.stdout.write(f"\rStarting scan in [{i:2}/{seconds}] seconds: [{bar:<{width}}]")
        sys.stdout.flush()
        time.sleep(1)
    print("\n")

def scan(adb_path, log):
    print("\n[SCAN RESULTS]")
    log.write("[SCAN RESULTS]\n")
    packages = get_installed_packages(adb_path)
    found = []

    for pkg, description in GOV_SPYWARE_PACKAGES.items():
        if pkg in packages:
            print(f"[❌] {description} ({pkg})")
            log.write(f"[DETECTED] {description} ({pkg})\n")
            found.append((pkg, description))
        else:
            print(f"[✅] {description} ({pkg})")
            log.write(f"[OK] {description} ({pkg})\n")

    if found:
        print("\n[ALERT] Spyware detected!")
        for pkg, desc in found:
            print(f"\nPackage: {pkg}\nDescription: {desc}\nRemoval: Use 'adb uninstall {pkg}' or perform a factory reset if pre-installed.\n")
            log.write(f"\nALERT: {pkg} - {desc}\n")
    else:
        print("\n[INFO] No government spyware detected.")
        log.write("\n[INFO] No spyware found.\n")

def main():
    adb_path = get_adb_path()
    if not adb_path:
        print("[ERROR] ADB not found. Make sure it is in tools/{windows,linux,mac}/")
        return

    log = start_log()
    log.write("SpyHunter Quick Start Log\n")

    print("\n[Quick Start] Android Government Spyware Scanner\n")
    print("Make sure USB Debugging is enabled on your Android device.")
    print("1. Go to 'Settings' > 'About Phone' > tap 'Build Number' 7 times to enable Developer Options.")
    print("2. Return to 'Settings' > 'Developer Options'.")
    print("3. Enable 'USB Debugging'.\n")

    choice = input("Press Enter when ready, or type 'esc' to return to the main menu: ").strip().lower()
    if choice == 'esc':
        log.close()
        return

    print("\n[INFO] Gathering device information...\n")
    phone_info = get_phone_info(adb_path)
    print("[DEVICE INFORMATION]\n")

    readable = {
        "ro.product.manufacturer": "Manufacturer",
        "ro.product.model": "Model",
        "ro.build.version.release": "Android Version",
        "ro.serialno": "Serial Number",
        "ro.build.version.sdk": "SDK Level",
        "ro.build.display.id": "Build ID"
    }

    for prop, label in readable.items():
        value = phone_info.get(prop, "Unknown")
        print(f"{label:<15}: {value}")
        log.write(f"{label}: {value}\n")

    print("\n[INFO] Initializing scan...")
    progress_bar(10)

    scan(adb_path, log)
    log.close()
    input("\nPress Enter to return to main menu...")
