#!/usr/bin/env python3
"""Full pipeline test for APNG Lip Sync Tool."""
import sys
sys.path.insert(0, '.')

from pathlib import Path
from test_image_analysis import create_test_face_image


def test_full_pipeline():
    """Test the complete lip sync pipeline."""
    print("=" * 60)
    print("APNG Lip Sync Tool - Full Pipeline Test")
    print("=" * 60)

    # 1. Create test image
    print("\n[1/5] Creating test image...")
    test_image = Path("uploads/test_pipeline.png")
    create_test_face_image(test_image)
    print(f"   ✓ Test image created: {test_image}")

    # 2. Test face detection
    print("\n[2/5] Testing face detection...")
    from src.face_detector import detect_face_regions
    try:
        result = detect_face_regions(test_image)
        if result["success"]:
            print(f"   ✓ Face detected with confidence: {result['regions'].get('confidence', 'N/A')}")
        else:
            print(f"   ! Detection returned: {result.get('error', 'Unknown')}")
    except Exception as e:
        print(f"   ✗ Face detection error: {e}")

    # 3. Test text to viseme conversion
    print("\n[3/5] Testing text to viseme conversion...")
    from src.text_to_viseme import korean_text_to_visemes, viseme_sequence_to_frames
    test_text = "안녕하세요"
    visemes = korean_text_to_visemes(test_text)
    frames = viseme_sequence_to_frames(visemes)
    print(f"   ✓ Text: '{test_text}'")
    print(f"   ✓ Viseme count: {len(visemes)}")
    print(f"   ✓ Frame count (24fps): {len(frames)}")
    print(f"   ✓ Viseme sequence: {[v['viseme'] for v in visemes[:5]]}...")

    # 4. Test TTS generation
    print("\n[4/5] Testing TTS generation...")
    from src.tts_engine import generate_speech_with_timing
    try:
        tts_result = generate_speech_with_timing(test_text)
        if tts_result["success"]:
            print(f"   ✓ Audio generated: {tts_result['path']}")
            print(f"   ✓ Duration: {tts_result['duration_ms']}ms")
            print(f"   ✓ Timing entries: {len(tts_result['timings'])}")
        else:
            print(f"   ✗ TTS failed")
    except Exception as e:
        print(f"   ✗ TTS error: {e}")

    # 5. Test APNG generation (with existing files)
    print("\n[5/5] Testing APNG generation logic...")
    from src.apng_generator import create_lipsync_sequence_apng
    from PIL import Image

    # Create dummy viseme images for testing
    test_char_dir = Path("characters/test_pipeline")
    test_char_dir.mkdir(parents=True, exist_ok=True)

    viseme_images = {}
    colors = {
        "rest": "#FFE4C4",
        "A": "#FF6B6B",
        "E": "#4ECDC4",
        "I": "#45B7D1",
        "O": "#96CEB4",
        "U": "#FFEAA7",
    }

    for viseme, color in colors.items():
        img = Image.new("RGB", (100, 100), color)
        path = test_char_dir / f"{viseme}.png"
        img.save(path)
        viseme_images[viseme] = path

    # Create test APNG
    test_sequence = ["rest", "A", "E", "I", "O", "U", "rest"]
    output_apng = Path("output/test_pipeline.png")

    try:
        result_path = create_lipsync_sequence_apng(
            viseme_sequence=test_sequence,
            viseme_images=viseme_images,
            output_path=output_apng,
            frame_delay=200,
            add_transitions=False
        )
        print(f"   ✓ APNG created: {result_path}")
    except Exception as e:
        print(f"   ✗ APNG error: {e}")

    print("\n" + "=" * 60)
    print("Pipeline test completed!")
    print("=" * 60)

    # Summary
    print("\n📁 Generated files:")
    print(f"   - Test image: uploads/test_pipeline.png")
    print(f"   - Test character: characters/test_pipeline/")
    print(f"   - Test APNG: output/test_pipeline.png")
    print(f"   - TTS audio: output/speech_*.mp3")

    print("\n🌐 To test the web interface:")
    print("   Open: https://tkim.planitai.co.jp/blog/20251208-make-apng-tool/public/")


if __name__ == "__main__":
    test_full_pipeline()
