#!/usr/bin/env python3
"""
Wildberries Product to Video Prompts Generator

Pipeline:
1. Extract product data from WB URL or manual input
2. Select best photo for video generation
3. Generate nanobanana prompts (cleanup + resize to 16:9)
4. Generate Veo3 video prompts (multiple scene options)

Usage:
    python wb_to_video_prompts.py <WB_URL>
    python wb_to_video_prompts.py --manual  # For manual JSON input
"""

import sys
import json
import re
from typing import Dict, List, Optional
from urllib.parse import urlparse, parse_qs

# Import fetcher if available (prefer Playwright over Selenium)
try:
    from wb_fetcher import fetch_wb_product_playwright
    HAS_FETCHER = True
    FETCHER_TYPE = "playwright"
except ImportError:
    try:
        from wb_fetcher_selenium import fetch_wb_product_selenium
        HAS_FETCHER = True
        FETCHER_TYPE = "selenium"
    except ImportError:
        HAS_FETCHER = False
        FETCHER_TYPE = None


def extract_product_id(url: str) -> Optional[str]:
    """Extract product ID from Wildberries URL"""
    # Pattern: /catalog/{ID}/detail.aspx
    match = re.search(r'/catalog/(\d+)/', url)
    if match:
        return match.group(1)
    return None


def construct_image_urls(product_id: str, num_images: int = 10) -> List[str]:
    """
    Construct image URLs for Wildberries product
    WB image URL pattern: https://basket-XX.wbbasket.ru/volXXXX/partXXXXXX/XXXXXXXX/images/big/N.webp
    """
    vol = int(product_id[:4])
    part = int(product_id[:6])

    # Determine basket number (simple hashing)
    basket_num = (int(product_id) % 20) + 1
    basket = f"basket-{basket_num:02d}"

    base_url = f"https://{basket}.wbbasket.ru/vol{vol}/part{part}/{product_id}/images/big"

    urls = []
    for i in range(1, num_images + 1):
        urls.append(f"{base_url}/{i}.webp")

    return urls


def select_best_photo(image_urls: List[str]) -> Dict:
    """
    Provide guidance for photo selection for video generation
    Returns selection criteria and recommended approach
    """
    return {
        "criteria": {
            "priority_1": "Clear product visibility - centered, well-lit, high contrast",
            "priority_2": "Minimal text overlays - avoid images with large price tags or badges",
            "priority_3": "Simple background - white/neutral or simple lifestyle setting",
            "priority_4": "Product in natural state - not extreme close-ups of details",
            "priority_5": "Good composition - product takes 40-70% of frame"
        },
        "recommended_approach": [
            "Download first 5-7 images from the product page",
            "Visually inspect each image",
            "Prefer images 1-3 (usually hero shots)",
            "Avoid images with multiple angles in one frame",
            "Check image resolution - should be at least 1024x1024"
        ],
        "image_urls": image_urls[:7],  # First 7 images usually best
        "automation_note": "For automation, analyze image with Claude Vision API first"
    }


def generate_nanobanana_prompt(product_type: str = "product", background: str = "white") -> Dict:
    """
    Generate nanobanana prompts for image cleanup and resize to 16:9
    """

    # Step 1: Cleanup
    if background == "white" or background == "studio":
        cleanup_prompt = (
            "Remove all text, watermarks, price tags, discount badges, and promotional overlays. "
            "Extend clean white background where text was removed. "
            "Preserve product details exactly."
        )
    elif background == "lifestyle":
        cleanup_prompt = (
            "Remove text overlays and watermarks. "
            "Inpaint the background naturally to match surrounding area. "
            "Do not alter the product itself."
        )
    else:
        cleanup_prompt = (
            "Remove all text overlays, watermarks, price tags, discount badges, and promotional labels. "
            "Keep the product intact. Clean background."
        )

    # Step 2: Resize to 16:9
    resize_prompt = (
        "Extend this image to 16:9 aspect ratio. "
        "Generate natural background on sides. "
        "Keep product centered and unchanged. "
        "Match lighting and style."
    )

    # Combined (recommended for single-step processing)
    combined_prompt = (
        f"1. {cleanup_prompt}\n"
        f"2. {resize_prompt}\n"
        "3. Ensure product remains perfectly centered and unchanged."
    )

    return {
        "approach": "two_step_recommended",
        "step_1_cleanup": cleanup_prompt,
        "step_2_resize": resize_prompt,
        "combined_single_step": combined_prompt,
        "output_aspect_ratio": "16:9",
        "notes": [
            "Two-step approach gives more control",
            "Single-step faster but may have quality trade-offs",
            "Always verify product details remain intact after processing"
        ]
    }


def generate_veo3_prompts(product_data: Dict) -> Dict:
    """
    Generate Veo3 video generation prompts based on product analysis
    Creates multiple scene options (single-scene + two-act)
    """

    product_name = product_data.get("name", "product")
    product_type = product_data.get("type", "general")

    prompts = {
        "metadata": {
            "product": product_name,
            "duration": "8 seconds",
            "aspect_ratio": "16:9",
            "resolution": "1920x1080"
        },
        "scenes": []
    }

    # Scene A1: Static Beauty Shot (Level 1 - Safest)
    scene_a1 = {
        "id": "A1",
        "format": "single-scene",
        "level": "1",
        "risk": "low",
        "title": "Static Beauty Shot",
        "scene": "STUDIO SETTING — SOFT DAYLIGHT",
        "duration": "8 seconds",
        "camera": {
            "starting_position": "matches input image exactly",
            "movement": "slow dolly push in",
            "speed": "slow",
            "lens": "50mm"
        },
        "lighting": {
            "base": "preserve from input image",
            "change": "subtle light sweep across product surface"
        },
        "subject": {
            "product": product_name,
            "initial_state": "as seen in input image",
            "action": "product remains static, light moves across surface revealing texture"
        },
        "preserve": [
            "product position",
            "background",
            "all product details"
        ],
        "negative_prompt": "--no text --no watermark --no logo --no warped surfaces --no morphing",
        "veo3_prompt": f"""INT. STUDIO SETTING / SOFT DAYLIGHT //
static to slow dolly push // 50mm lens // shallow depth of field

SUBJECT: {product_name}, centered on clean background

ACTION: camera slowly pushes toward product, subtle light sweep reveals texture and details

MOOD: clean, minimal, commercial, premium

--no text --no watermark --no logo --no warped surfaces --no morphing"""
    }
    prompts["scenes"].append(scene_a1)

    # Scene A2: Product Motion (Level 2)
    scene_a2 = {
        "id": "A2",
        "format": "single-scene",
        "level": "2",
        "risk": "low-medium",
        "title": "Product with Rotation",
        "scene": "STUDIO SETTING — SOFT DAYLIGHT",
        "duration": "8 seconds",
        "camera": {
            "starting_position": "matches input image exactly",
            "movement": "slow arc right",
            "speed": "slow",
            "lens": "50mm"
        },
        "subject": {
            "product": product_name,
            "initial_state": "as seen in input image",
            "action": "camera arcs slowly around product revealing different angles"
        },
        "preserve": [
            "product integrity",
            "background consistency"
        ],
        "negative_prompt": "--no text --no watermark --no warped surfaces --no product deformation --no morphing",
        "veo3_prompt": f"""INT. STUDIO SETTING / SOFT DAYLIGHT //
slow arc camera movement // 50mm lens // shallow depth of field

SUBJECT: {product_name}, centered, pristine condition

ACTION: camera slowly arcs right around product, revealing form and details from different angles

MOOD: clean, elegant, commercial, premium

--no text --no watermark --no warped surfaces --no product deformation --no morphing"""
    }
    prompts["scenes"].append(scene_a2)

    # Scene B1: Two-Act Lifestyle (requires product type context)
    scene_b1 = {
        "id": "B1",
        "format": "two-act",
        "concept": "Product Discovery to Lifestyle Context",
        "emotional_arc": "from curiosity to desire",
        "total_duration": "8 seconds",
        "act_1": {
            "duration": "2.5 seconds",
            "scene": "exact scene from input image",
            "camera": {
                "starting_position": "matches input exactly",
                "movement": "slow push in",
                "speed": "slow"
            },
            "action": "camera moves toward product, establishing hero moment",
            "lighting": "preserve from input",
            "purpose": "anchor — viewer locks onto product"
        },
        "act_2": {
            "duration": "5.5 seconds",
            "scene": "LIFESTYLE SETTING — determined by product type",
            "camera": {
                "position": "medium shot, natural angle",
                "movement": "slow pan or static",
                "speed": "slow"
            },
            "action": "product in natural use context, aspirational setting",
            "lighting": "natural lighting, warm tones",
            "mood": "aspirational, relatable, desirable",
            "transition_from_act1": "fade through white",
            "purpose": "payoff — viewer desires product"
        },
        "preserve_across_acts": [
            "product exact appearance",
            "product color and key features"
        ],
        "negative_prompt": "--no text --no watermark --no scene blending --no product alteration --no morphing",
        "veo3_prompt": f"""ACT 1 (2.5 sec):
INT. STUDIO / SOFT DAYLIGHT
slow push toward {product_name}
Product hero moment — clean, pristine

[FADE THROUGH WHITE]

ACT 2 (5.5 sec):
INT/EXT. LIFESTYLE SETTING / NATURAL LIGHT
Same {product_name} in natural use context
Aspirational but relatable scene
Warm lighting, lived-in feel

MOOD: from professional to personal, curiosity to desire

--no text --no watermark --no scene blending --no product alteration --no morphing"""
    }
    prompts["scenes"].append(scene_b1)

    return prompts


def generate_complete_pipeline(product_url: str, product_data: Optional[Dict] = None, fetch_live: bool = False) -> Dict:
    """
    Complete pipeline: WB URL → Photo selection → Nanobanana → Veo3 prompts
    """

    # Extract product ID
    product_id = extract_product_id(product_url)
    if not product_id:
        return {"error": "Could not extract product ID from URL"}

    # Try to fetch live data if requested
    if fetch_live and HAS_FETCHER and not product_data:
        print(f"Fetching product data from Wildberries ({FETCHER_TYPE})...")
        if FETCHER_TYPE == "playwright":
            product_data = fetch_wb_product_playwright(product_url, headless=True)
        else:
            product_data = fetch_wb_product_selenium(product_url, headless=True)
        if product_data:
            print(f"✓ Fetched: {product_data.get('name', 'Unknown')}")
            image_urls = product_data.get('images', [])
        else:
            print("✗ Failed to fetch, using fallback image URLs")
            image_urls = construct_image_urls(product_id)
    else:
        # Generate image URLs
        image_urls = construct_image_urls(product_id)

    # Photo selection guidance
    photo_selection = select_best_photo(image_urls)

    # Generate nanobanana prompts
    nanobanana = generate_nanobanana_prompt()

    # Generate Veo3 prompts
    # If no product data provided, use generic
    if not product_data:
        product_data = {
            "name": f"Product {product_id}",
            "type": "general"
        }

    veo3_prompts = generate_veo3_prompts(product_data)

    # Complete output
    return {
        "pipeline": "wb_to_video",
        "product_id": product_id,
        "product_url": product_url,
        "step_1_photo_selection": photo_selection,
        "step_2_image_processing": nanobanana,
        "step_3_video_generation": veo3_prompts,
        "workflow_summary": [
            "1. Download product images from WB",
            "2. Select best image using provided criteria",
            "3. Process with nanobanana: cleanup + resize to 16:9",
            "4. Generate video with Veo3 using provided prompts",
            "5. Review and select best video variant"
        ]
    }


def main():
    if len(sys.argv) < 2:
        print(__doc__)
        print("\nOptions:")
        print("  --fetch     Fetch live data from WB using Playwright")
        print("  --manual    Enter product data manually")
        sys.exit(1)

    fetch_live = "--fetch" in sys.argv

    if "--manual" in sys.argv:
        print("Manual mode: Please provide product data as JSON")
        print("Format: {\"name\": \"Product Name\", \"type\": \"category\", \"url\": \"WB URL\"}")
        product_json = input("Paste JSON: ")
        try:
            product_data = json.loads(product_json)
            result = generate_complete_pipeline(product_data["url"], product_data, fetch_live=False)
        except json.JSONDecodeError:
            print("Invalid JSON")
            sys.exit(1)
    else:
        # Get URL (filter out flags)
        urls = [arg for arg in sys.argv[1:] if not arg.startswith('--')]
        if not urls:
            print("Error: No URL provided")
            sys.exit(1)

        product_url = urls[0]
        result = generate_complete_pipeline(product_url, fetch_live=fetch_live)

    # Output as formatted JSON
    print(json.dumps(result, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()
