# app/api_client.py
import requests
import os

def generate_lip_sync_via_api(api_url, video_path, audio_path, output_path=None):
    """
    Sends video and audio to your Flask Wav2Lip API.
    Downloads the generated output video to output_path (if provided).

    Args:
        api_url (str): Base URL of the running Flask API (e.g. "http://127.0.0.1:5001")
        video_path (str): Path to input face video file.
        audio_path (str): Path to input audio file.
        output_path (str, optional): Path to save returned lip-synced video.

    Returns:
        str: Local path to saved output video or None if failed.
    """
    try:
        # Ensure files exist
        if not os.path.exists(video_path):
            raise FileNotFoundError(f"Video file not found: {video_path}")
        if not os.path.exists(audio_path):
            raise FileNotFoundError(f"Audio file not found: {audio_path}")

        files = {
            "video": open(video_path, "rb"),
            "audio": open(audio_path, "rb")
        }

        print("[INFO] Sending request to Flask API...")
        response = requests.post(f"{api_url}/api/lipsync", files=files)

        if response.status_code == 200:
            # Save output video if provided
            if output_path:
                with open(output_path, "wb") as f:
                    f.write(response.content)
                print(f"[DONE] Lip-synced video saved to: {output_path}")
                return output_path
            else:
                print("[DONE] Lip-synced video received (no save path provided).")
                return "Success"
        else:
            print(f"[ERROR] API returned status {response.status_code}: {response.text}")
            return None

    except Exception as e:
        print(f"[ERROR] API call failed: {e}")
        return None
