#!/usr/bin/env python
"""
Example of RTMP streaming in FMUS-VID.

This script demonstrates how to stream video to RTMP servers like YouTube or Twitch.
"""

import sys
import os
import time
from pathlib import Path

# Add the parent directory to the path so we can import fmusvid
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from fmusvid.core.stream import CameraStream, RTMPStream
from fmusvid.core.video import Video
from fmusvid.operations.text import TextOverlay
from PIL import Image, ImageDraw, ImageFont

def stream_from_camera(rtmp_url):
    """Stream from camera to RTMP server."""

    print(f"Streaming camera feed to {rtmp_url}")
    print("Press Ctrl+C to stop streaming")

    # Create the camera stream (default camera)
    with CameraStream(width=1280, height=720, fps=30) as camera:
        # Create the RTMP stream
        with RTMPStream(rtmp_url, width=1280, height=720) as rtmp:
            # Create text overlay for timestamp
            font = ImageFont.load_default()

            try:
                # Stream until interrupted
                start_time = time.time()
                while True:
                    # Read frame from camera
                    frame = camera.read()

                    if frame is not None:
                        # Add timestamp overlay
                        draw = ImageDraw.Draw(frame)
                        timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
                        elapsed = time.time() - start_time
                        text = f"{timestamp} (Elapsed: {elapsed:.1f}s)"
                        draw.text((10, 10), text, fill="white", font=font)

                        # Write frame to RTMP stream
                        rtmp.write(frame)

                    # Sleep to maintain frame rate
                    time.sleep(1/30)
            except KeyboardInterrupt:
                print("\nStreaming stopped")

def stream_from_video(video_path, rtmp_url):
    """Stream a video file to RTMP server."""

    print(f"Streaming video {video_path} to {rtmp_url}")
    print("Press Ctrl+C to stop streaming")

    # Load the video
    video = Video(video_path)
    info = video.info()

    # Create the RTMP stream
    with RTMPStream(rtmp_url, width=info.width, height=info.height, fps=info.fps) as rtmp:
        # Open the video file with OpenCV for frame reading
        import cv2
        cap = cv2.VideoCapture(str(video_path))

        if not cap.isOpened():
            print(f"Error: Could not open video {video_path}")
            return

        try:
            # Stream until interrupted or end of video
            start_time = time.time()
            frame_count = 0

            while True:
                # Read frame from video
                ret, frame = cap.read()

                if not ret:
                    # End of video, loop back to beginning
                    cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
                    continue

                # Convert from BGR to RGB for PIL
                frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                pil_frame = Image.fromarray(frame_rgb)

                # Add stream overlay
                draw = ImageDraw.Draw(pil_frame)
                elapsed = time.time() - start_time
                text = f"LIVE: {elapsed:.1f}s"
                draw.text((10, 10), text, fill="red")

                # Write frame to RTMP stream
                rtmp.write(pil_frame)

                # Sleep to maintain frame rate
                frame_count += 1
                target_time = start_time + (frame_count / info.fps)
                current_time = time.time()

                if current_time < target_time:
                    time.sleep(target_time - current_time)

        except KeyboardInterrupt:
            print("\nStreaming stopped")
        finally:
            cap.release()

def main():
    """Run the RTMP streaming example."""
    print("FMUS-VID RTMP Streaming Example")
    print("==============================")

    # Get streaming parameters
    print("\nWhat would you like to stream?")
    print("1. Camera feed")
    print("2. Video file")
    choice = input("Enter choice (1/2): ")

    # Get RTMP URL
    rtmp_url = input("\nEnter RTMP URL (e.g., rtmp://live.twitch.tv/app/your-key): ")

    if choice == "1":
        stream_from_camera(rtmp_url)
    elif choice == "2":
        video_path = input("Enter path to video file: ")
        stream_from_video(video_path, rtmp_url)
    else:
        print("Invalid choice")

if __name__ == "__main__":
    main()
