#!/usr/bin/env python3
"""
Import showcase videos from good-generations.md file.

This is a one-time migration script to populate the showcase database
from the manually curated list of good generations.

Usage:
    python import_showcase.py [--dry-run]
"""

import argparse
import os
import sys
from pathlib import Path

from database import (
    init_showcase_db,
    add_showcase_video,
    get_showcase_video_by_task,
    get_showcase_videos_count,
)


def parse_line(line: str) -> dict:
    """
    Parse a line from good-generations.md.

    Format: /mnt/video/wb_XXXXX/YYYYMMDD_HHMMSS_xxxx/videos/video.mp4 -- note

    Returns:
        Dict with video_path, task_id, product_id, rating, has_artifacts
    """
    line = line.strip()
    if not line or line.startswith("#"):
        return None

    # Split path and note
    parts = line.split(" -- ", 1)
    video_path = parts[0].strip()
    note = parts[1].strip() if len(parts) > 1 else None

    # Validate path format
    if not video_path.startswith("/mnt/video/wb_"):
        return None

    # Extract product_id and task_id from path
    # Path format: /mnt/video/wb_XXXXX/YYYYMMDD_HHMMSS_xxxx/videos/video.mp4
    try:
        path_parts = video_path.split("/")
        # path_parts: ['', 'mnt', 'video', 'wb_14797921', '20260121_150943_gnqe', 'videos', 'video.mp4']
        product_dir = path_parts[3]  # 'wb_14797921'
        task_id = path_parts[4]  # '20260121_150943_gnqe'
        product_id = product_dir.replace("wb_", "")
    except (IndexError, ValueError):
        return None

    # Determine rating and artifacts from note
    has_artifacts = False
    rating = 0

    if note:
        note_lower = note.lower()
        if "артефакты" in note_lower or "артефакт" in note_lower:
            has_artifacts = True
        if "отлично" in note_lower:
            rating = 5

    return {
        "video_path": video_path,
        "task_id": task_id,
        "product_id": product_id,
        "rating": rating,
        "has_artifacts": has_artifacts,
        "note": note,
    }


def import_from_file(file_path: str, dry_run: bool = False) -> dict:
    """
    Import videos from a file.

    Args:
        file_path: Path to the good-generations.md file
        dry_run: If True, only show what would be imported

    Returns:
        Dict with counts: total, added, skipped, errors
    """
    results = {
        "total": 0,
        "added": 0,
        "skipped": 0,
        "already_exists": 0,
        "errors": 0,
        "with_artifacts": 0,
        "excellent": 0,
    }

    with open(file_path, "r", encoding="utf-8") as f:
        for line_num, line in enumerate(f, 1):
            parsed = parse_line(line)
            if parsed is None:
                continue

            results["total"] += 1

            # Check if video file exists
            if not os.path.exists(parsed["video_path"]):
                print(f"  [SKIP] Line {line_num}: File not found: {parsed['video_path']}")
                results["skipped"] += 1
                continue

            # Check if already in showcase
            existing = get_showcase_video_by_task(parsed["task_id"])
            if existing:
                print(f"  [EXISTS] {parsed['task_id']}")
                results["already_exists"] += 1
                continue

            # Track stats
            if parsed["has_artifacts"]:
                results["with_artifacts"] += 1
            if parsed["rating"] == 5:
                results["excellent"] += 1

            if dry_run:
                status = []
                if parsed["has_artifacts"]:
                    status.append("ARTIFACTS")
                if parsed["rating"] == 5:
                    status.append("EXCELLENT")
                status_str = f" [{', '.join(status)}]" if status else ""
                print(f"  [DRY-RUN] Would add: {parsed['task_id']}{status_str}")
                results["added"] += 1
            else:
                video_id = add_showcase_video(
                    video_path=parsed["video_path"],
                    task_id=parsed["task_id"],
                    product_id=parsed["product_id"],
                    rating=parsed["rating"],
                    has_artifacts=parsed["has_artifacts"],
                    added_by=0  # System import
                )
                if video_id:
                    status = []
                    if parsed["has_artifacts"]:
                        status.append("ARTIFACTS")
                    if parsed["rating"] == 5:
                        status.append("EXCELLENT")
                    status_str = f" [{', '.join(status)}]" if status else ""
                    print(f"  [ADDED] ID={video_id} {parsed['task_id']}{status_str}")
                    results["added"] += 1
                else:
                    print(f"  [ERROR] Failed to add: {parsed['task_id']}")
                    results["errors"] += 1

    return results


def main():
    parser = argparse.ArgumentParser(description="Import showcase videos from good-generations.md")
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="Only show what would be imported, don't actually import"
    )
    parser.add_argument(
        "--file",
        type=str,
        default="/home/videobot/dev/docs/good-generations.md",
        help="Path to good-generations.md file"
    )
    args = parser.parse_args()

    print("=" * 60)
    print("Showcase Video Import")
    print("=" * 60)

    if args.dry_run:
        print("MODE: Dry run (no changes will be made)")
    else:
        print("MODE: Live import")

    print(f"FILE: {args.file}")
    print()

    # Check file exists
    if not os.path.exists(args.file):
        print(f"ERROR: File not found: {args.file}")
        sys.exit(1)

    # Initialize database (always needed to check existing videos)
    init_showcase_db()

    # Get initial count
    initial_count = get_showcase_videos_count(active_only=False, exclude_artifacts=False)

    print(f"Current showcase count: {initial_count}")
    print()
    print("Processing...")
    print("-" * 40)

    results = import_from_file(args.file, dry_run=args.dry_run)

    print("-" * 40)
    print()
    print("Results:")
    print(f"  Total lines processed: {results['total']}")
    print(f"  Added: {results['added']}")
    print(f"  Already exists: {results['already_exists']}")
    print(f"  Skipped (file not found): {results['skipped']}")
    print(f"  Errors: {results['errors']}")
    print()
    print(f"  Videos with artifacts: {results['with_artifacts']}")
    print(f"  Excellent videos (rating=5): {results['excellent']}")

    if not args.dry_run:
        final_count = get_showcase_videos_count(active_only=False, exclude_artifacts=False)
        clean_count = get_showcase_videos_count(active_only=True, exclude_artifacts=True)
        print()
        print(f"Final showcase count: {final_count}")
        print(f"Clean videos (active, no artifacts): {clean_count}")

    print()
    print("=" * 60)


if __name__ == "__main__":
    main()
