#!/usr/bin/env python3
"""
Download a sample of WB product videos and analyze them.

For each product:
1. Get video URL from Sellematics
2. Get content history (when video was added)
3. Download 360p MP4
4. Check duration with ffprobe
5. Compare video-added date vs our generation date
6. Save to /mnt/video/wb_{product_id}/downloaded-video/{datetime}/
"""

import sqlite3
import requests
import subprocess
import time
import sys
import json
from datetime import datetime, timezone
from pathlib import Path

DB_PATH = "/mnt/video/videobot_prod.db"
SELLEMATICS_URL = "http://127.0.0.1:43761/api/v1"

# Admin/test accounts to exclude
EXCLUDE_USERS = {100000001, 100000002, 100000003}

SAMPLE_SIZE = 20


def get_products_with_video_from_report():
    """Load products with video from the previous check report."""
    report_path = "/tmp/wb_video_check_report.json"
    if not Path(report_path).exists():
        print(f"ERROR: Run check_wb_videos.py first to generate {report_path}")
        sys.exit(1)
    with open(report_path) as f:
        report = json.load(f)
    return report["products_with_video"]


def get_generation_dates(product_id: str) -> list:
    """Get our generation dates for this product from the database."""
    conn = sqlite3.connect(DB_PATH)
    cur = conn.cursor()
    cur.execute("""
        SELECT t.task_id, t.created_at, t.user_id, u.username, u.first_name
        FROM transactions t
        JOIN users u ON t.user_id = u.user_id
        WHERE t.type = 'generation'
          AND t.product_id = ?
          AND t.user_id NOT IN ({})
          AND NOT EXISTS (
              SELECT 1 FROM transactions r
              WHERE r.type = 'refund' AND r.task_id = t.task_id
          )
        ORDER BY t.created_at
    """.format(",".join(str(u) for u in EXCLUDE_USERS)), (product_id,))
    rows = cur.fetchall()
    conn.close()
    return [
        {"task_id": r[0], "date": r[1], "user_id": r[2],
         "username": r[3], "first_name": r[4]}
        for r in rows
    ]


def get_content_history(product_id: str) -> list:
    """Get content change history from Sellematics (image/video counts over time)."""
    try:
        resp = requests.post(
            f"{SELLEMATICS_URL}/archive/product/content",
            data={"mall": "wb", "id": product_id},
            timeout=30,
        )
        if resp.status_code != 200:
            return []
        data = resp.json()
        return data.get("payload", [])
    except Exception as e:
        print(f"    WARNING: Content history failed: {e}")
        return []


def find_video_added_date(history: list) -> dict:
    """Analyze content history to find when video was first added."""
    if not history:
        return {"video_added_ts": None, "video_added_date": None, "history_points": 0}

    sorted_hist = sorted(history, key=lambda x: x["ts"])

    # Find first transition from videos=0 to videos>0
    prev_videos = None
    for rec in sorted_hist:
        content = rec.get("content", {})
        cur_videos = content.get("videos", 0)

        if prev_videos is not None and prev_videos == 0 and cur_videos > 0:
            ts = rec["ts"]
            dt = datetime.fromtimestamp(ts, tz=timezone.utc)
            return {
                "video_added_ts": ts,
                "video_added_date": dt.strftime("%Y-%m-%d %H:%M:%S UTC"),
                "history_points": len(sorted_hist),
            }
        prev_videos = cur_videos

    # If video count is >0 in the very first record, video was added before tracking
    first_content = sorted_hist[0].get("content", {})
    if first_content.get("videos", 0) > 0:
        ts = sorted_hist[0]["ts"]
        dt = datetime.fromtimestamp(ts, tz=timezone.utc)
        return {
            "video_added_ts": ts,
            "video_added_date": f"before {dt.strftime('%Y-%m-%d')} (already present at tracking start)",
            "history_points": len(sorted_hist),
        }

    # Video count is 0 throughout history but Sellematics currently shows video
    # This means Sellematics content history hasn't caught up yet
    return {
        "video_added_ts": None,
        "video_added_date": "not detected in history (recent add or Sellematics lag)",
        "history_points": len(sorted_hist),
    }


def get_video_duration(filepath: str) -> float:
    """Get video duration in seconds using ffprobe."""
    try:
        result = subprocess.run(
            ["ffprobe", "-v", "quiet", "-print_format", "json",
             "-show_format", "-show_streams", filepath],
            capture_output=True, text=True, timeout=10
        )
        data = json.loads(result.stdout)
        duration = float(data.get("format", {}).get("duration", 0))
        # Also get resolution
        streams = data.get("streams", [])
        video_stream = next((s for s in streams if s.get("codec_type") == "video"), {})
        width = video_stream.get("width", 0)
        height = video_stream.get("height", 0)
        return duration, width, height
    except Exception as e:
        print(f"    WARNING: ffprobe failed: {e}")
        return 0.0, 0, 0


def download_video(url: str, save_path: Path) -> bool:
    """Download video from URL."""
    try:
        resp = requests.get(url, timeout=30, stream=True)
        if resp.status_code != 200:
            print(f"    ERROR: Download failed HTTP {resp.status_code}")
            return False
        save_path.parent.mkdir(parents=True, exist_ok=True)
        with open(save_path, "wb") as f:
            for chunk in resp.iter_content(chunk_size=8192):
                f.write(chunk)
        size_kb = save_path.stat().st_size / 1024
        print(f"    Downloaded: {size_kb:.0f} KB")
        return True
    except Exception as e:
        print(f"    ERROR: Download failed: {e}")
        return False


def main():
    now = datetime.now()
    now_str = now.strftime("%Y%m%d_%H%M%S")

    print("Loading report from previous check...")
    products = get_products_with_video_from_report()
    print(f"Found {len(products)} products with video\n")

    # Take a sample
    sample = products[:SAMPLE_SIZE]
    print(f"Processing sample of {len(sample)} products...\n")

    results = []
    ours_likely = 0
    ours_unlikely = 0

    for i, prod in enumerate(sample):
        pid = prod["product_id"]
        name = prod["name"][:50]
        video_urls = prod.get("videos", [])
        users = prod.get("users", [])

        print(f"[{i+1}/{len(sample)}] {pid} | {name}")
        print(f"  WB: https://www.wildberries.ru/catalog/{pid}/detail.aspx")

        if not video_urls:
            print("  SKIP: no video URL in report")
            continue

        video_url = video_urls[0]
        print(f"  Video URL: {video_url}")

        # Get our generation dates
        gen_dates = get_generation_dates(pid)
        print(f"  Our generations: {len(gen_dates)}")
        for g in gen_dates:
            print(f"    {g['date']} by @{g['username'] or g['first_name']}")

        # Get content history from Sellematics
        history = get_content_history(pid)
        video_info = find_video_added_date(history)
        print(f"  Video added: {video_info['video_added_date']} ({video_info['history_points']} history points)")

        # Download video
        save_dir = Path(f"/mnt/video/wb_{pid}/downloaded-video/{now_str}")
        save_path = save_dir / "video_360p.mp4"

        downloaded = download_video(video_url, save_path)
        duration = 0.0
        width = height = 0

        if downloaded:
            duration, width, height = get_video_duration(str(save_path))
            print(f"  Duration: {duration:.1f}s | Resolution: {width}x{height}")

        # Analyze: is this likely our video?
        likely_ours = False
        reason = ""
        if duration > 0:
            if 7.0 <= duration <= 11.0:
                likely_ours = True
                reason = f"duration {duration:.1f}s matches our 8-10s range"
                ours_likely += 1
            else:
                reason = f"duration {duration:.1f}s doesn't match our range"
                ours_unlikely += 1
        else:
            reason = "could not determine duration"

        verdict = "LIKELY OURS" if likely_ours else "PROBABLY NOT OURS"
        print(f"  Verdict: {verdict} ({reason})")

        # Build result record
        result = {
            "product_id": pid,
            "name": prod["name"],
            "wb_url": f"https://www.wildberries.ru/catalog/{pid}/detail.aspx",
            "video_url": video_url,
            "downloaded_to": str(save_path) if downloaded else None,
            "download_time": now.isoformat(),
            "source": "sellematics",
            "video_duration_sec": round(duration, 2),
            "video_resolution": f"{width}x{height}" if width else None,
            "video_added_date": video_info["video_added_date"],
            "video_added_ts": video_info["video_added_ts"],
            "history_points": video_info["history_points"],
            "our_generations": gen_dates,
            "likely_ours": likely_ours,
            "verdict": verdict,
            "verdict_reason": reason,
        }
        results.append(result)

        # Save per-product log
        if downloaded:
            log_path = save_dir / "download_log.json"
            with open(log_path, "w", encoding="utf-8") as f:
                json.dump(result, f, ensure_ascii=False, indent=2, default=str)

        print()
        time.sleep(0.5)  # Rate limit Sellematics

    # Summary
    print(f"\n{'='*80}")
    print(f"SUMMARY: {len(results)} products analyzed")
    print(f"{'='*80}\n")
    print(f"  Likely ours (8-10s):  {ours_likely}")
    print(f"  Probably not ours:    {ours_unlikely}")

    if results:
        print(f"\n  --- Likely ours ---")
        for r in results:
            if r["likely_ours"]:
                gens = r["our_generations"]
                user = gens[0]["username"] or gens[0]["first_name"] if gens else "?"
                print(f"  {r['product_id']} | {r['video_duration_sec']}s | {r['name'][:40]} | @{user}")
                print(f"    Video added: {r['video_added_date']}")
                if gens:
                    print(f"    Our gen:     {gens[0]['date']}")

        print(f"\n  --- Probably not ours ---")
        for r in results:
            if not r["likely_ours"]:
                print(f"  {r['product_id']} | {r['video_duration_sec']}s | {r['name'][:40]}")
                print(f"    Reason: {r['verdict_reason']}")

    # Save full report
    report_path = f"/tmp/wb_video_sample_{now_str}.json"
    full_report = {
        "run_time": now.isoformat(),
        "sample_size": len(sample),
        "likely_ours": ours_likely,
        "probably_not_ours": ours_unlikely,
        "results": results,
    }
    with open(report_path, "w", encoding="utf-8") as f:
        json.dump(full_report, f, ensure_ascii=False, indent=2, default=str)
    print(f"\nFull report saved to: {report_path}")


if __name__ == "__main__":
    main()
