#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "websockets",
#     "httpx",
#     "tqdm",
# ]
# ///

import asyncio
import json
import os
import sys
import time
import httpx
import websockets
from tqdm import tqdm

VIDEOS_DIR = "/home/flancian/Burup/videos"
MANIFEST_PATH = "/home/flancian/Burup/burup_videos_manifest.json"
STATE_PATH = "/home/flancian/Burup/.downloaded_videos_map.json"

async def download_all_videos():
    if not os.path.exists(MANIFEST_PATH):
        print(f"Videos manifest not found at {MANIFEST_PATH}", flush=True)
        return

    with open(MANIFEST_PATH, "r", encoding="utf-8") as f:
        videos = json.load(f)

    os.makedirs(VIDEOS_DIR, exist_ok=True)

    # Load existing state
    downloaded_map = {}
    if os.path.exists(STATE_PATH):
        try:
            with open(STATE_PATH, "r", encoding="utf-8") as f:
                downloaded_map = json.load(f)
        except Exception:
            downloaded_map = {}

    # Check disk for existing {vid_id}.mp4 files
    for v in videos:
        vid_id = v["id"]
        mp4_path = os.path.join(VIDEOS_DIR, f"{vid_id}.mp4")
        if os.path.exists(mp4_path) and os.path.getsize(mp4_path) > 1024:
            if vid_id not in downloaded_map:
                downloaded_map[vid_id] = {
                    "filename": f"{vid_id}.mp4",
                    "size_bytes": os.path.getsize(mp4_path),
                    "label": v.get("label", "")
                }

    # Filter pending
    pending = [v for v in videos if v["id"] not in downloaded_map]
    print(f"Total Burup videos: {len(videos)} | Already on disk: {len(downloaded_map)} | Pending: {len(pending)}", flush=True)

    if not pending:
        print("All Burup videos have already been downloaded!", flush=True)
        return

    # Find active Google Photos tab
    async with httpx.AsyncClient() as client:
        try:
            resp = await client.get("http://localhost:9222/json")
            tabs = resp.json()
        except Exception as e:
            print(f"Error connecting to Chromium DevTools: {e}", flush=True)
            return

    target_tab = None
    for tab in tabs:
        url = tab.get("url", "")
        if tab.get("type") == "page" and "photos.google.com" in url:
            target_tab = tab
            break

    if not target_tab:
        print("No Google Photos tab found on port 9222.", flush=True)
        return

    tab_id = target_tab["id"]
    print(f"Activating tab {tab_id} ({target_tab.get('title')})...", flush=True)
    async with httpx.AsyncClient() as client:
        try:
            await client.get(f"http://localhost:9222/json/activate/{tab_id}")
        except Exception:
            pass

    ws_url = target_tab.get("webSocketDebuggerUrl")

    async with websockets.connect(ws_url, max_size=50 * 1024 * 1024) as ws:
        msg_id = 1
        async def send_cmd(method, params=None):
            nonlocal msg_id
            cmd = {"id": msg_id, "method": method, "params": params or {}}
            msg_id += 1
            await ws.send(json.dumps(cmd))
            while True:
                res = await ws.recv()
                data = json.loads(res)
                if data.get("id") == cmd["id"]:
                    return data

        await send_cmd("Page.bringToFront")

        # Set download directory
        await send_cmd("Page.setDownloadBehavior", {
            "behavior": "allow",
            "downloadPath": VIDEOS_DIR
        })

        progress = tqdm(total=len(videos), initial=len(downloaded_map), desc="Downloading Lady Burup Videos")

        for idx, video in enumerate(pending, 1):
            vid_id = video["id"]
            label = video.get("label", "")
            photo_url = f"https://photos.google.com/photo/{vid_id}"
            target_mp4 = os.path.join(VIDEOS_DIR, f"{vid_id}.mp4")

            if os.path.exists(target_mp4) and os.path.getsize(target_mp4) > 1024:
                downloaded_map[vid_id] = {"filename": f"{vid_id}.mp4", "size_bytes": os.path.getsize(target_mp4), "label": label}
                progress.update(1)
                continue

            start_time = time.time()

            # Navigate to video page
            await send_cmd("Page.navigate", {"url": photo_url})
            await asyncio.sleep(3.5)

            # Focus window & body
            await send_cmd("Runtime.evaluate", {"expression": "window.focus(); document.body.focus();"})

            # Send Shift+D
            for attempt in range(2):
                await send_cmd("Input.dispatchKeyEvent", {"type": "keyDown", "key": "Shift", "code": "ShiftLeft", "windowsVirtualKeyCode": 16})
                await send_cmd("Input.dispatchKeyEvent", {"type": "keyDown", "key": "D", "code": "KeyD", "windowsVirtualKeyCode": 68, "modifiers": 8, "text": "D"})
                await send_cmd("Input.dispatchKeyEvent", {"type": "keyUp", "key": "D", "code": "KeyD", "windowsVirtualKeyCode": 68, "modifiers": 8})
                await send_cmd("Input.dispatchKeyEvent", {"type": "keyUp", "key": "Shift", "code": "ShiftLeft", "windowsVirtualKeyCode": 16})
                await asyncio.sleep(1.0)
                # Quick check if file already started
                recent = [f for f in os.listdir(VIDEOS_DIR) if os.path.getmtime(os.path.join(VIDEOS_DIR, f)) >= start_time - 1.0]
                if any(f.endswith(".crdownload") or f.endswith(".mp4") or f.endswith(".mov") for f in recent):
                    break

            # Wait for download to finish
            download_file = None
            for _ in range(40):
                await asyncio.sleep(1.0)
                recent = [f for f in os.listdir(VIDEOS_DIR) if os.path.getmtime(os.path.join(VIDEOS_DIR, f)) >= start_time - 1.0]
                crdownloads = [f for f in recent if f.endswith(".crdownload")]
                finished = [f for f in recent if not f.endswith(".crdownload") and (f.endswith(".mp4") or f.endswith(".mov") or f.endswith(".jpg"))]

                if finished and not crdownloads:
                    # Pick the finished file that is not an existing photo ID
                    candidates = [f for f in finished if not f.startswith(vid_id)]
                    if candidates:
                        download_file = candidates[0]
                        break
                    elif finished:
                        download_file = finished[0]
                        break

            if download_file:
                download_path = os.path.join(VIDEOS_DIR, download_file)
                # Wait briefly for file write lock release
                await asyncio.sleep(0.5)
                file_size = os.path.getsize(download_path)

                # Rename to {vid_id}.mp4 if it was a downloaded video
                if download_file.endswith(".mp4") or download_file.endswith(".mov"):
                    if download_path != target_mp4:
                        try:
                            os.rename(download_path, target_mp4)
                        except Exception as e:
                            print(f"Rename error: {e}", flush=True)

                    downloaded_map[vid_id] = {
                        "filename": f"{vid_id}.mp4",
                        "orig_name": download_file,
                        "size_bytes": file_size,
                        "label": label
                    }
                    progress.set_postfix_str(f"{vid_id[:8]} ({file_size // (1024*1024)}MB)")
                elif download_file.endswith(".jpg"):
                    # Motion photo or still image
                    downloaded_map[vid_id] = {
                        "filename": download_file,
                        "is_still": True,
                        "size_bytes": file_size,
                        "label": label
                    }
                    progress.set_postfix_str(f"{vid_id[:8]} (still photo)")
            else:
                downloaded_map[vid_id] = {
                    "filename": None,
                    "error": "Timeout / No download initiated",
                    "label": label
                }
                progress.set_postfix_str("Timeout")

            # Checkpoint
            if idx % 3 == 0 or idx == len(pending):
                with open(STATE_PATH, "w", encoding="utf-8") as f:
                    json.dump(downloaded_map, f, indent=2)

            progress.update(1)
            await asyncio.sleep(0.8)

        progress.close()
        print(f"\nCompleted! Videos preserved in {VIDEOS_DIR}", flush=True)

if __name__ == "__main__":
    asyncio.run(download_all_videos())
