#!/usr/bin/env python3
"""
Check which products generated by our bot have videos uploaded to Wildberries.

Queries the prod database for successful generations by real users,
then checks each product via Sellematics API for video presence.
"""

import sqlite3
import requests
import time
import sys
import json
from concurrent.futures import ThreadPoolExecutor, as_completed

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

# Admin/test accounts to exclude
EXCLUDE_USERS = {
    100000001,   # developer
    100000002,   # project owner
    100000003,   # tester
}


def get_product_ids():
    """Get unique product IDs from successful generations by real users."""
    conn = sqlite3.connect(DB_PATH)
    cur = conn.cursor()
    cur.execute("""
        SELECT DISTINCT t.product_id
        FROM transactions t
        WHERE t.type = 'generation'
          AND t.product_id IS NOT NULL
          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.product_id
    """.format(",".join(str(u) for u in EXCLUDE_USERS)))
    rows = cur.fetchall()
    conn.close()
    return [r[0] for r in rows]


def get_product_users():
    """Get product_id -> list of user info for successful generations."""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    cur = conn.cursor()
    cur.execute("""
        SELECT t.product_id, t.user_id, u.username, u.first_name, t.created_at
        FROM transactions t
        JOIN users u ON t.user_id = u.user_id
        WHERE t.type = 'generation'
          AND t.product_id IS NOT NULL
          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_users = {}
    for row in cur.fetchall():
        pid = row["product_id"]
        if pid not in product_users:
            product_users[pid] = []
        product_users[pid].append({
            "user_id": row["user_id"],
            "username": row["username"],
            "first_name": row["first_name"],
            "date": row["created_at"],
        })
    conn.close()
    return product_users


def check_video(product_id: str) -> dict:
    """Check if a WB product has video via Sellematics API."""
    try:
        resp = requests.post(
            SELLEMATICS_URL,
            data={"mall": "wb", "id": product_id},
            timeout=15,
        )
        if resp.status_code != 200:
            return {"product_id": product_id, "has_video": None, "name": "?",
                    "video_count": 0, "videos": [], "error": f"HTTP {resp.status_code}"}

        text = resp.text.strip()
        if not text:
            return {"product_id": product_id, "has_video": None, "name": "?",
                    "video_count": 0, "videos": [], "error": "empty response"}

        data = resp.json()

        # Sellematics wraps in {"products": [{"current": {...}}]}
        products = data.get("products", [])
        if not products:
            return {"product_id": product_id, "has_video": None, "name": "NOT FOUND",
                    "video_count": 0, "videos": [], "error": "product not found"}

        current = products[0].get("current", {})
        name = current.get("name", "?")
        videos = current.get("videos", [])
        count_videos = current.get("countVideos", 0)
        has_video = count_videos > 0 or len(videos) > 0

        return {
            "product_id": product_id,
            "has_video": has_video,
            "name": name,
            "video_count": max(count_videos, len(videos)),
            "videos": videos,
            "error": None,
        }
    except Exception as e:
        return {"product_id": product_id, "has_video": None, "name": "?",
                "video_count": 0, "videos": [], "error": str(e)}


def main():
    print("Fetching product IDs from database...")
    product_ids = get_product_ids()
    product_users = get_product_users()
    print(f"Found {len(product_ids)} unique products from real users\n")

    # Check Sellematics availability
    print("Testing Sellematics API...")
    try:
        test = requests.post(SELLEMATICS_URL, data={"mall": "wb", "id": "645744957"}, timeout=10)
        if test.status_code != 200:
            print(f"ERROR: Sellematics returned HTTP {test.status_code}")
            sys.exit(1)
        print("Sellematics API is available\n")
    except Exception as e:
        print(f"ERROR: Cannot reach Sellematics: {e}")
        print("Make sure sellematics-tunnel service is running")
        sys.exit(1)

    print(f"Checking {len(product_ids)} products via Sellematics (4 workers, rate-limited)...\n")

    results = []
    with_video = []
    without_video = []
    errors = []

    # Use fewer workers to avoid overwhelming Sellematics
    with ThreadPoolExecutor(max_workers=4) as executor:
        futures = {}
        for i, pid in enumerate(product_ids):
            future = executor.submit(check_video, pid)
            futures[future] = pid
            # Small delay between submissions to rate-limit
            if i % 4 == 3:
                time.sleep(0.3)

        done = 0
        for future in as_completed(futures):
            done += 1
            result = future.result()
            results.append(result)

            if result["error"]:
                errors.append(result)
            elif result["has_video"]:
                with_video.append(result)
            else:
                without_video.append(result)

            if done % 50 == 0:
                print(f"  Checked {done}/{len(product_ids)} "
                      f"(video: {len(with_video)}, no video: {len(without_video)}, errors: {len(errors)})...")

    # Sort results
    with_video.sort(key=lambda x: x["product_id"])
    without_video.sort(key=lambda x: x["product_id"])

    # Print results
    print(f"\n{'='*80}")
    print(f"RESULTS: {len(product_ids)} products checked")
    print(f"{'='*80}\n")

    reachable = len(with_video) + len(without_video)
    print(f"  WITH video:    {len(with_video)}")
    print(f"  WITHOUT video: {len(without_video)}")
    print(f"  Errors:        {len(errors)}")

    if reachable > 0:
        conversion = len(with_video) / reachable * 100
        print(f"\n  Conversion rate: {conversion:.1f}% of reachable products have video uploaded")

    if with_video:
        print(f"\n{'='*80}")
        print(f"PRODUCTS WITH VIDEO ({len(with_video)}):")
        print(f"{'='*80}\n")

        for r in with_video:
            pid = r["product_id"]
            name = r["name"][:60]
            users = product_users.get(pid, [])
            user_info = ", ".join(
                f"@{u['username']}" if u['username'] else f"{u['first_name']}({u['user_id']})"
                for u in users[:3]
            )
            gen_count = len(users)
            url = f"https://www.wildberries.ru/catalog/{pid}/detail.aspx"
            vid_urls = r.get("videos", [])

            print(f"  {pid} | {name}")
            print(f"    URL: {url}")
            print(f"    Users ({gen_count} gen): {user_info}")
            if vid_urls:
                for v in vid_urls:
                    print(f"    Video: {v}")
            print()

    if errors:
        print(f"\n{'='*80}")
        print(f"ERRORS ({len(errors)}):")
        print(f"{'='*80}\n")
        for r in errors[:20]:
            print(f"  {r['product_id']}: {r['error']}")
        if len(errors) > 20:
            print(f"  ... and {len(errors) - 20} more")

    # Save JSON report
    report = {
        "total_products": len(product_ids),
        "with_video": len(with_video),
        "without_video": len(without_video),
        "errors": len(errors),
        "conversion_rate": len(with_video) / max(1, reachable) * 100 if reachable else 0,
        "products_with_video": [
            {
                "product_id": r["product_id"],
                "name": r["name"],
                "url": f"https://www.wildberries.ru/catalog/{r['product_id']}/detail.aspx",
                "videos": r.get("videos", []),
                "users": product_users.get(r["product_id"], []),
            }
            for r in with_video
        ],
    }

    report_path = "/tmp/wb_video_check_report.json"
    with open(report_path, "w", encoding="utf-8") as f:
        json.dump(report, f, ensure_ascii=False, indent=2, default=str)
    print(f"\nFull report saved to: {report_path}")


if __name__ == "__main__":
    main()
