"""
Video generation service using Replicate.

- Text-to-video: lightricks/ltx-2-distilled
- Image-to-video: lightricks/ltx-2-distilled (with image input)
"""

import replicate
from loguru import logger

# Models
LTX_MODEL = "lightricks/ltx-2-distilled"

# Old models (commented out — switch back if needed)
# T2V_MODEL = "wan-video/wan-2.2-t2v-fast"
# I2V_MODEL = "wan-video/wan-2.2-i2v-fast"



async def generate_video(
    prompt: str,
    image_url: str | None = None,
    num_frames: int = 121,
) -> dict:
    """Generate a video using Replicate's lightricks/ltx-2-distilled model.

    Args:
        prompt: Text description of the video to generate.
        image_url: Optional reference image URL for image-to-video.
        num_frames: Number of frames (default 121).

    Returns:
        dict with "url" key on success, or "error" key on failure.
    """
    try:
        logger.info(f"[VideoService] Generating video (ltx-2-distilled): {prompt!r}")

        input_params = {
            "prompt": prompt,
            "num_frames": num_frames,
            "aspect_ratio": "16:9",
            "enhance_prompt": False,
            "image_strength": 1,
        }

        if image_url:
            input_params["image"] = image_url

        output = await replicate.async_run(LTX_MODEL, input=input_params)

        # Old wan-video model (commented out — switch back if needed)
        # model = I2V_MODEL if image_url else T2V_MODEL
        # input_params = {
        #     "prompt": prompt,
        #     "go_fast": True,
        #     "num_frames": num_frames,
        #     "resolution": "480p",
        #     "sample_shift": 12,
        #     "frames_per_second": 16,
        #     "interpolate_output": False,
        #     "lora_scale_transformer": 1,
        #     "lora_scale_transformer_2": 1,
        # }
        # if image_url:
        #     input_params["image"] = image_url
        # output = await replicate.async_run(model, input=input_params)

        if output:
            url = str(output.url) if hasattr(output, "url") else str(output)
            logger.info(f"[VideoService] Video generated: {url}")
            return {"url": url, "success": True}

        logger.warning("[VideoService] No video returned from Replicate")
        return {"error": "No video was generated. Please try again.", "success": False}

    except Exception as e:
        logger.error(f"[VideoService] Error generating video: {e}")
        return {"error": str(e), "success": False}
