import subprocess
import time
from datetime import datetime

nfc_keywords = ["RF_INTF_ACTIVATED_NTF"]
log_file = "nfc_tag_read_log.txt"
summary_file = "nfc_summary.txt"
iterations = 2000  # 可調整為 2000

seen_tags = set()
tag_log_per_iteration = []

def log_message(message):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    line = f"[{timestamp}] {message}"
    print(line)
    with open(log_file, "a", encoding="utf-8") as f:
        f.write(line + "\n")

def extract_unique_tag_line(log_output):
    lines = log_output.splitlines()
    for line in lines:
        if any(keyword in line for keyword in nfc_keywords):
            tag_data = line.strip()
            if tag_data not in seen_tags:
                seen_tags.add(tag_data)
                return tag_data
    return None

log_message("=== NFC Stress Test Start ===")
for i in range(1, iterations + 1):
    log_message(f"\n--- Iteration {i} ---")

    # 開啟 NFC
    subprocess.run(["adb", "shell", "svc", "nfc", "enable"])
    time.sleep(7)

    # 擷取 logcat
    result = subprocess.run(["adb", "logcat", "-d"], capture_output=True, text=True, encoding="utf-8", errors="ignore")    
    tag_line = extract_unique_tag_line(result.stdout)

    if tag_line:
        log_message(f"✅ Tag detected:\n{tag_line}")
        tag_log_per_iteration.append((i, tag_line))
    else:
        log_message("❌ No new tag detected.")
        tag_log_per_iteration.append((i, None))

    # 清除 logcat 避免重複
    subprocess.run(["adb", "logcat", "-c"], encoding="utf-8", errors="ignore")

    # 關閉 NFC
    subprocess.run(["adb", "shell", "svc", "nfc", "disable"])
    time.sleep(7)

log_message("\n=== NFC Stress Test Completed ===")

# 產出 summary
with open(summary_file, "w", encoding="utf-8") as f:
    success_count = sum(1 for _, tag in tag_log_per_iteration if tag)
    f.write(f"NFC Tag Detection Summary ({success_count}/{iterations} successful)\n")
    f.write("=" * 50 + "\n")
    for idx, tag in tag_log_per_iteration:
        if tag:
            f.write(f"Iteration {idx}: ✅ {tag}\n")
        else:
            f.write(f"Iteration {idx}: ❌ No tag\n")

print(f"\n✅ Summary written to {summary_file}")
