import re
import os
import subprocess
import json
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

baseurl=os.getenv("BASE_URL")

def check_line(line, result):
    for segment in result["segments"]:
        if line in segment["text"]:
            return segment["end"]
    return None

def extract_timeframes(transcript):
    pattern = re.compile(r"\[(\d+\.\d+) - (\d+\.\d+)\] Question: (.*?)\n\[(\d+\.\d+) - (\d+\.\d+)\] Answer: (.*?)\n", re.DOTALL)
    
    qa_pairs = []
    for match in pattern.finditer(transcript):
        question_start, question_end, question_text, answer_start, answer_end, answer_text = match.groups()
        qa_pairs.append({
            "question": {
                "start_time": float(question_start),
                "end_time": float(question_end),
                "text": question_text.strip()
            },
            "answer": {
                "start_time": float(answer_start),
                "end_time": float(answer_end),
                "text": answer_text.strip()
            }
        })
    
    return qa_pairs


def trim_video(input_video, output_dir, time_frames):
    """Trims the video based on given time frames and saves each segment."""
    
    # Ensure the output directory exists
    os.makedirs(output_dir, exist_ok=True)

    short_files = []


    for idx, frame in enumerate(time_frames):
        start_time = frame['start_time']
        end_time = frame['end_time']
        output_video = os.path.join(output_dir, f"clip_{idx+1}.mp4")

        command = [
            "ffmpeg", "-i", input_video, "-ss", str(start_time), "-to", str(end_time),
            "-c:v", "libx264", "-c:a", "aac", "-strict", "experimental", "-y", output_video
        ]

        print(f"Processing clip {idx+1}: {output_video}")
        video_url = baseurl + output_video
        short_files.append(video_url)

        subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

    print("✅ All video clips have been successfully trimmed!")
    return short_files