#!/usr/bin/env python3
"""
Fetch video URLs from WB product pages using Playwright.
For products where Sellematics doesn't have the video URL yet.
Downloads the video and checks duration.
"""

import json
import re
import subprocess
import requests
import time
import sys
from datetime import datetime
from pathlib import Path


# Products with has_video=True in card.json but no video URL from Sellematics
PRODUCTS_TO_CHECK = [
    "120494441", "139410943", "160465576", "162622144",
    "207200149", "221029462", "224402547", "252159055",
    "343883846", "3586328", "372799044", "387711555",
    "3889504", "389507827", "390183791", "390189254",
    "499133961", "5528319", "599069295", "608346645",
    "645704467", "650880410", "659670513", "77987903",
    "804979524", "811294730",
]


def extract_video_urls(page) -> list:
    """Extract video URLs from WB product page."""
    return page.evaluate("""() => {
        const videos = [];

        // Method 1: Direct video elements
        document.querySelectorAll('video').forEach(v => {
            const src = v.src || v.getAttribute('src');
            if (src && !src.startsWith('blob:') && src.includes('mp4')) {
                videos.push(src);
            }
            // Check source children
            v.querySelectorAll('source').forEach(s => {
                const ssrc = s.src || s.getAttribute('src');
                if (ssrc && !ssrc.startsWith('blob:') && ssrc.includes('mp4')) {
                    videos.push(ssrc);
                }
            });
        });

        // Method 2: video-js elements
        document.querySelectorAll('video-js video, .vjs-tech').forEach(v => {
            const src = v.src || v.getAttribute('src');
            if (src && !src.startsWith('blob:') && src.includes('mp4')) {
                videos.push(src);
            }
        });

        // Method 3: Look for videonme URLs in any attribute
        const allEls = document.querySelectorAll('[src*="videonme"], [data-src*="videonme"], [poster*="videonme"]');
        allEls.forEach(el => {
            ['src', 'data-src'].forEach(attr => {
                const val = el.getAttribute(attr);
                if (val && val.includes('videonme') && val.includes('mp4')) {
                    videos.push(val);
                }
            });
        });

        // Deduplicate
        return [...new Set(videos)];
    }""")


def main():
    from playwright.sync_api import sync_playwright

    now_str = datetime.now().strftime("%Y%m%d_%H%M%S")
    results = []

    print(f"Checking {len(PRODUCTS_TO_CHECK)} products via Playwright...\n")

    with sync_playwright() as p:
        browser = p.chromium.launch(
            headless=True,
            args=['--disable-blink-features=AutomationControlled', '--no-sandbox']
        )
        context = browser.new_context(
            viewport={"width": 1920, "height": 1080},
            user_agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            locale="ru-RU"
        )
        page = context.new_page()
        page.add_init_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined});")

        for i, pid in enumerate(PRODUCTS_TO_CHECK):
            url = f"https://www.wildberries.ru/catalog/{pid}/detail.aspx"
            print(f"[{i+1}/{len(PRODUCTS_TO_CHECK)}] {pid}...", end=" ", flush=True)

            try:
                page.goto(url, wait_until="networkidle", timeout=30000)
                time.sleep(2)

                # Try to find video
                video_urls = extract_video_urls(page)

                # Also check page source for videonme URLs as fallback
                if not video_urls:
                    content = page.content()
                    found = re.findall(r'https://videonme-basket-\d+\.wbbasket\.ru/[^"\']+\.mp4', content)
                    video_urls = list(set(found))

                if not video_urls:
                    print("no video found on page")
                    results.append({"product_id": pid, "video_url": None, "error": "no video on page"})
                    continue

                video_url = video_urls[0]
                print(f"found: {video_url[:80]}...", flush=True)

                # Download
                save_dir = Path(f"/mnt/video/wb_{pid}/downloaded-video/{now_str}")
                save_path = save_dir / "video_wb_360p.mp4"
                save_dir.mkdir(parents=True, exist_ok=True)

                resp = requests.get(video_url, timeout=30, stream=True)
                if resp.status_code == 200:
                    with open(save_path, "wb") as f:
                        for chunk in resp.iter_content(8192):
                            f.write(chunk)

                    # Get duration
                    probe = subprocess.run(
                        ["ffprobe", "-v", "quiet", "-show_entries", "format=duration",
                         "-of", "csv=p=0", str(save_path)],
                        capture_output=True, text=True, timeout=10)
                    wb_dur = float(probe.stdout.strip()) if probe.stdout.strip() else 0

                    # Get our video duration
                    our_videos = list(Path(f"/mnt/video/wb_{pid}").glob("*/videos/video.mp4"))
                    our_dur = 0
                    if our_videos:
                        our_video = sorted(our_videos)[-1]  # latest
                        probe2 = subprocess.run(
                            ["ffprobe", "-v", "quiet", "-show_entries", "format=duration",
                             "-of", "csv=p=0", str(our_video)],
                            capture_output=True, text=True, timeout=10)
                        our_dur = float(probe2.stdout.strip()) if probe2.stdout.strip() else 0

                    # Classify
                    if 6.8 <= wb_dur <= 7.2:
                        verdict = "OURS_8s"
                    elif 7.3 <= wb_dur <= 7.7:
                        verdict = "OURS_10s"
                    elif wb_dur < 1:
                        verdict = "UNKNOWN"
                    else:
                        verdict = "NOT_OURS"

                    print(f"  WB={wb_dur:.1f}s OURS={our_dur:.1f}s → {verdict}")

                    results.append({
                        "product_id": pid,
                        "video_url": video_url,
                        "wb_duration": round(wb_dur, 3),
                        "our_duration": round(our_dur, 3),
                        "verdict": verdict,
                        "downloaded_to": str(save_path),
                    })

                    # Save per-product log
                    with open(save_dir / "download_log.json", "w") as f:
                        json.dump(results[-1], f, ensure_ascii=False, indent=2)
                else:
                    print(f"  download failed: HTTP {resp.status_code}")
                    results.append({"product_id": pid, "video_url": video_url, "error": f"HTTP {resp.status_code}"})

            except Exception as e:
                print(f"error: {str(e)[:60]}")
                results.append({"product_id": pid, "video_url": None, "error": str(e)[:100]})

            time.sleep(1)

        browser.close()

    # Summary
    ours = [r for r in results if r.get("verdict", "").startswith("OURS")]
    not_ours = [r for r in results if r.get("verdict") == "NOT_OURS"]
    no_video = [r for r in results if r.get("error")]

    print(f"\n{'='*60}")
    print(f"RESULTS: {len(PRODUCTS_TO_CHECK)} products checked")
    print(f"{'='*60}")
    print(f"  Ours (by duration):  {len(ours)}")
    print(f"  Not ours:            {len(not_ours)}")
    print(f"  No video/error:      {len(no_video)}")

    if ours:
        print(f"\n  OUR VIDEOS:")
        for r in ours:
            print(f"    {r['product_id']} | WB={r['wb_duration']}s | {r['verdict']}")
            print(f"      https://www.wildberries.ru/catalog/{r['product_id']}/detail.aspx")

    # Save report
    report_path = f"/tmp/wb_playwright_video_check_{now_str}.json"
    with open(report_path, "w") as f:
        json.dump({"results": results, "ours": len(ours), "not_ours": len(not_ours)}, f, indent=2)
    print(f"\nReport: {report_path}")


if __name__ == "__main__":
    main()
