import os
import sys
import warnings

# Hỗ trợ in tiếng Việt trên console Windows
if hasattr(sys.stdout, 'reconfigure'):
    try:
        sys.stdout.reconfigure(encoding='utf-8')
    except Exception:
        pass

# Đảm bảo ffmpeg trong venv/Scripts có trong PATH
venv_scripts = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'venv', 'Scripts')
if venv_scripts not in os.environ['PATH']:
    os.environ['PATH'] = venv_scripts + os.pathsep + os.environ['PATH']

import whisper

warnings.filterwarnings("ignore")

def generate_english_subtitles(video_path, output_srt_path, model_name="tiny"):
    print(f"Đang phân tích âm thanh và tạo Subtitle tiếng Anh cho: {os.path.basename(video_path)}")
    
    # Load model (tiny/base phù hợp chạy CPU nhanh gọn)
    model = whisper.load_model(model_name)
    
    # Transcribe and translate to English
    result = model.transcribe(video_path, task="translate")
    
    # Hàm ghi ra định dạng SRT
    def format_timestamp(seconds):
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        seconds = seconds % 60
        milliseconds = int((seconds - int(seconds)) * 1000)
        return f"{hours:02d}:{minutes:02d}:{int(seconds):02d},{milliseconds:03d}"

    with open(output_srt_path, "w", encoding="utf-8") as srt_file:
        for i, segment in enumerate(result["segments"], start=1):
            start = format_timestamp(segment["start"])
            end = format_timestamp(segment["end"])
            text = segment["text"].strip()
            srt_file.write(f"{i}\n{start} --> {end}\n{text}\n\n")
            
    print(f"Đã lưu Subtitle tiếng Anh tại: {output_srt_path}")
    return output_srt_path
