"""Gemini API client for image analysis and generation."""
import base64
from pathlib import Path
from google import genai
from google.genai import types
from .config import GOOGLE_API_KEY, GEMINI_MODEL, GEMINI_IMAGE_MODEL


def get_client():
    """Get Gemini client instance."""
    return genai.Client(api_key=GOOGLE_API_KEY)


def analyze_face_image(image_path: str | Path) -> dict:
    """
    Analyze a face image to extract features for lip sync generation.

    Args:
        image_path: Path to the image file

    Returns:
        dict with face analysis results
    """
    client = get_client()
    image_path = Path(image_path)

    # Read and encode image
    with open(image_path, "rb") as f:
        image_data = f.read()

    # Create image part
    image_part = types.Part.from_bytes(
        data=image_data,
        mime_type=f"image/{image_path.suffix[1:].lower()}"
    )

    prompt = """Analyze this face image for lip sync animation creation.

Please identify and describe:
1. Face position and angle (frontal, 3/4 view, etc.)
2. Mouth region location and shape
3. Art style (realistic photo, anime, cartoon, etc.)
4. Skin tone and lip color
5. Any distinctive features around the mouth area

Return the analysis in a structured format."""

    response = client.models.generate_content(
        model=GEMINI_MODEL,
        contents=[prompt, image_part]
    )

    return {
        "analysis": response.text,
        "image_path": str(image_path)
    }


def generate_viseme_image(
    original_image_path: str | Path,
    viseme: str,
    viseme_description: str,
    output_path: str | Path
) -> Path:
    """
    Generate a viseme (mouth shape) variation of the original image.

    Args:
        original_image_path: Path to the original face image
        viseme: Viseme code (A, E, I, O, U, etc.)
        viseme_description: Description of the mouth shape
        output_path: Path to save the generated image

    Returns:
        Path to the generated image
    """
    client = get_client()
    original_image_path = Path(original_image_path)
    output_path = Path(output_path)

    # Read original image
    with open(original_image_path, "rb") as f:
        image_data = f.read()

    image_part = types.Part.from_bytes(
        data=image_data,
        mime_type=f"image/{original_image_path.suffix[1:].lower()}"
    )

    prompt = f"""Edit this face image to change ONLY the mouth shape.

Target mouth shape: {viseme} - {viseme_description}

Instructions:
1. Keep the face, eyes, hair, and all other features exactly the same
2. Only modify the mouth/lips area
3. The mouth should show: {viseme_description}
4. Maintain the same art style and quality
5. The transition should look natural

Generate the edited image with the new mouth shape."""

    response = client.models.generate_content(
        model=GEMINI_IMAGE_MODEL,
        contents=[prompt, image_part],
        config=types.GenerateContentConfig(
            response_modalities=["IMAGE", "TEXT"]
        )
    )

    # Extract and save the generated image
    for part in response.candidates[0].content.parts:
        if part.inline_data and part.inline_data.mime_type.startswith("image/"):
            image_bytes = part.inline_data.data
            output_path.parent.mkdir(parents=True, exist_ok=True)
            with open(output_path, "wb") as f:
                f.write(image_bytes)
            return output_path

    raise ValueError("No image generated in response")


def test_connection() -> bool:
    """Test the Gemini API connection."""
    try:
        client = get_client()
        response = client.models.generate_content(
            model=GEMINI_MODEL,
            contents="Say 'API connection successful' in one line."
        )
        print(f"API Test: {response.text}")
        return True
    except Exception as e:
        print(f"API Test Failed: {e}")
        return False
