"""
Taildrop Auto-Sender for VideoDetection.
Tự động phát hiện khi thiết bị iPhone (iphone-12-pro-max) online trên Tailscale
và tự động chuyển file qua tính năng Taildrop.
Chạy thường trực ở chế độ chờ (Standby daemon).
"""
import sys
import subprocess
import time
from pathlib import Path

# Đảm bảo UTF-8 an toàn trên Windows console chống lỗi cp1252
if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")
if hasattr(sys.stderr, "reconfigure"):
    sys.stderr.reconfigure(encoding="utf-8")

source_zip = Path(r"c:\Projects\VideoDetection_Source.zip")
full_zip = Path(r"c:\Projects\VideoDetection_Full.zip")

print("[Taildrop Daemon] Đang chạy thường trực chờ iphone-12-pro-max online...")

sent_source = False
sent_full = False

while not (sent_source and sent_full):
    try:
        status_proc = subprocess.run(["tailscale", "status"], capture_output=True, text=True, timeout=8)
        lines = [line for line in status_proc.stdout.splitlines() if "iphone-12-pro-max" in line]
        if lines:
            line = lines[0]
            if "offline" not in line.lower():
                print(f"[Taildrop] Phát hiện iphone-12-pro-max đang ACTIVE! Bắt đầu chuyển file...")
                if not sent_source and source_zip.exists():
                    res = subprocess.run(
                        ["tailscale", "file", "cp", str(source_zip), "iphone-12-pro-max:"],
                        capture_output=True,
                        text=True,
                        timeout=30,
                    )
                    if res.returncode == 0:
                        print("[Taildrop OK] Đã gửi thành công VideoDetection_Source.zip sang iPhone!")
                        sent_source = True
                    else:
                        print(f"[Taildrop Error Source] {res.stderr}")

                if not sent_full and full_zip.exists():
                    res = subprocess.run(
                        ["tailscale", "file", "cp", str(full_zip), "iphone-12-pro-max:"],
                        capture_output=True,
                        text=True,
                        timeout=120,
                    )
                    if res.returncode == 0:
                        print("[Taildrop OK] Đã gửi thành công VideoDetection_Full.zip sang iPhone!")
                        sent_full = True
                    else:
                        print(f"[Taildrop Error Full] {res.stderr}")

                if sent_source and sent_full:
                    print("[Taildrop Daemon] Hoàn tất toàn bộ file chuyển sang iPhone!")
                    break
    except Exception as e:
        pass
    time.sleep(10)
