#!/usr/bin/env python3
"""Generate all viseme images for a character."""
import sys
import json
import shutil
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))

from src.config import CHARACTERS_DIR, VISEME_SET
from src.gemini_client import generate_viseme_image


def generate_all_visemes(image_path: str, character_name: str) -> dict:
    """Generate all viseme images for a character.

    Args:
        image_path: Path to the original face image
        character_name: Name for the character

    Returns:
        dict with generation results
    """
    image_path = Path(image_path)
    if not image_path.exists():
        return {"error": f"Image not found: {image_path}"}

    # Create character directory
    char_dir = CHARACTERS_DIR / character_name
    char_dir.mkdir(parents=True, exist_ok=True)

    # Copy original as rest pose
    rest_path = char_dir / "rest.png"
    shutil.copy(image_path, rest_path)

    generated = ["rest"]
    errors = []

    # Generate each viseme
    for viseme, description in VISEME_SET.items():
        if viseme == "rest":
            continue

        output_path = char_dir / f"{viseme}.png"
        try:
            generate_viseme_image(
                original_image_path=image_path,
                viseme=viseme,
                viseme_description=description,
                output_path=output_path
            )
            generated.append(viseme)
            print(f"Generated: {viseme}", file=sys.stderr)
        except Exception as e:
            errors.append({"viseme": viseme, "error": str(e)})
            print(f"Error generating {viseme}: {e}", file=sys.stderr)

    # Save character config
    config = {
        "name": character_name,
        "original_image": str(image_path),
        "visemes": {v: str(char_dir / f"{v}.png") for v in generated},
        "errors": errors
    }

    config_path = char_dir / "config.json"
    with open(config_path, "w") as f:
        json.dump(config, f, indent=2)

    return {
        "success": True,
        "character_name": character_name,
        "generated": generated,
        "errors": errors
    }


if __name__ == "__main__":
    if len(sys.argv) < 3:
        print(json.dumps({"error": "Usage: generate_visemes.py <image_path> <character_name>"}))
        sys.exit(1)

    image_path = sys.argv[1]
    character_name = sys.argv[2]

    result = generate_all_visemes(image_path, character_name)
    print(json.dumps(result))
