"""Capture only; no Android input, login, or API/DB operation."""
from pathlib import Path
import subprocess
from shutil import copy2
from datetime import datetime
from PIL import Image

root = Path(r'C:\Users\Asus\Desktop\TourAppProject\travelin_app\docs\thesis_appendices')
inbox = root / 'work/capture_inbox'
for role in ('tourist', 'agency'):
    (inbox / role).mkdir(parents=True, exist_ok=True)
stamp = datetime.now().strftime('%Y%m%d_%H%M%S')
target = inbox / 'tourist' / 'tourist_profile.png'
if target.exists():
    target = target.with_name(f'tourist_profile_{stamp}.png')
adb = r'C:\Users\Asus\AppData\Local\Android\Sdk\platform-tools\adb.exe'
r = subprocess.run([adb, '-s', 'emulator-5554', 'exec-out', 'screencap', '-p'], capture_output=True, timeout=20)
if r.returncode != 0 or not r.stdout.startswith(b'\x89PNG\r\n\x1a\n'):
    raise SystemExit('SCREENSHOT_CAPTURE_FAILED')
target.write_bytes(r.stdout)
with Image.open(target) as im:
    im.verify()
for role, name, source in (
    ('tourist', 'tourist_profile_user_supplied.png', r'C:\Users\Asus\AppData\Local\Temp\codex-clipboard-dfbf4d3c-6cf9-44b5-acb2-108164601d88.png'),
    ('agency', 'agency_dashboard.png', r'C:\Users\Asus\AppData\Local\Temp\codex-clipboard-63f39915-66ec-417e-be51-0914900ded86.png'),
):
    dest = inbox / role / name
    if dest.exists():
        dest = dest.with_name(f'{dest.stem}_{stamp}.png')
    copy2(source, dest)
    print('PRESERVED', dest)
print('ADB_CAPTURE', target)
