import os
import subprocess

def get_video_duration(file_path):
    """영상 전체 길이를 초 단위로 반환"""
    cmd = [
        'ffprobe', '-v', 'error', '-show_entries', 'format=duration',
        '-of', 'default=noprint_wrappers=1:nokey=1', file_path
    ]
    try:
        output = subprocess.check_output(cmd).decode('utf-8').strip()
        return float(output)
    except:
        return 0.0

def timestamp_to_seconds(timestamp):
    """MM:SS 또는 SS 형식을 초 단위로 변환"""
    if isinstance(timestamp, (int, float)):
        return float(timestamp)
    try:
        parts = str(timestamp).split(':')
        if len(parts) == 2:
            return int(parts[0]) * 60 + int(parts[1])
        return float(parts[0])
    except:
        return 0.0

def seconds_to_timestamp(seconds):
    """초 단위를 MM:SS 형식으로 변환"""
    m = int(seconds // 60)
    s = int(seconds % 60)
    return f"{m:02d}:{s:02d}"

def clip_video(input_path, output_path, center_sec, window_seconds=90):
    """center_sec를 기준으로 앞뒤 window_seconds만큼 자름"""
    duration = get_video_duration(input_path)
    if duration == 0:
        return False
    
    start_sec = max(0, center_sec - window_seconds)
    end_sec = min(duration, start_sec + (window_seconds * 2))
    
    if (end_sec - start_sec) < (window_seconds * 2) and start_sec > 0:
        start_sec = max(0, end_sec - (window_seconds * 2))
    
    actual_duration = end_sec - start_sec

    # 임시 파일 경로
    temp_output = output_path + ".tmp.mp4"
    
    cmd = [
        'ffmpeg', '-y', '-ss', f"{start_sec:.2f}", '-t', f"{actual_duration:.2f}",
        '-i', input_path, '-c', 'copy', temp_output
    ]
    
    try:
        subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        if os.path.exists(output_path):
            os.remove(output_path)
        os.rename(temp_output, output_path)
        return True
    except:
        # copy 실패 시 재인코딩
        cmd[7:9] = ['-c:v', 'libx264', '-crf', '23', '-c:a', 'aac']
        try:
            subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            if os.path.exists(temp_output):
                if os.path.exists(output_path): os.remove(output_path)
                os.rename(temp_output, output_path)
            return True
        except:
            if os.path.exists(temp_output): os.remove(temp_output)
            return False

def append_to_url_list(file_path, url, timestamp, task):
    """youtube_url.txt에 데이터 추가"""
    line = f"{url}, {timestamp}, {task}\n"
    # 파일이 없으면 헤더 추가
    exists = os.path.exists(file_path)
    with open(file_path, 'a', encoding='utf-8') as f:
        if not exists:
            f.write("# URL, MM:SS, TaskName\n")
        f.write(line)

def get_url_list(file_path):
    """youtube_url.txt 파일을 읽어서 리스트로 반환"""
    if not os.path.exists(file_path):
        return []
    
    urls = []
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            parts = [p.strip() for p in line.split(',')]
            if len(parts) >= 3:
                urls.append({
                    'url': parts[0],
                    'timestamp': parts[1],
                    'task': parts[2]
                })
    return urls

def get_next_index(directory, prefix):
    """
    directory 내에서 {prefix}_{index:04d}.mp4 형식의 파일들을 찾아 
    가장 높은 index + 1을 반환함. 파일이 없으면 1 반환.
    """
    if not os.path.exists(directory):
        return 1
    
    max_idx = 0
    pattern = f"{prefix}_"
    for filename in os.listdir(directory):
        if filename.startswith(pattern) and filename.endswith(".mp4"):
            try:
                # {prefix}_0001.mp4 -> 0001 추출
                idx_part = filename[len(pattern):].split('.')[0]
                idx = int(idx_part)
                if idx > max_idx:
                    max_idx = idx
            except (ValueError, IndexError):
                continue
                
    return max_idx + 1
