import os
import subprocess
from datetime import datetime, timedelta
from typing import IO

from config import FFMPEG_EXEC, VIDEO_BITRATE, FFMPEG_USE_GPU, VIDEO_CLIP_EACH_SEC, VIDEO_CLIP_OVERFLOW_SEC, PROD_ENV, \
    FFMPEG_USE_INTEL_GPU


def get_video_real_duration(filename):
    ffmpeg_process = subprocess.Popen([
        "ffmpeg", "-hide_banner", "-progress", "-", "-v", "0", "-i", filename, "-c", "copy", "-f", "null", "-"
    ], stdout=subprocess.PIPE)
    return handle_ffmpeg_output(ffmpeg_process.stdout)


def encode_video_with_subtitles(orig_filename: str, subtitles: list[str], new_filename: str):
    if FFMPEG_USE_GPU:
        if FFMPEG_USE_INTEL_GPU:
            print("[+]Use Intel VAAPI Acceleration")
            encode_process = subprocess.Popen([
                FFMPEG_EXEC, "-hide_banner", "-progress", "-", "-v", "0", "-y",
                "-hwaccel", "vaapi", "-i", orig_filename, "-vf",
                ",".join("subtitles=%s" % i for i in subtitles) + ",hwupload",
                "-c:a", "copy", "-c:v", "h264_vaapi",
                "-f", "mp4", "-preset:v", "fast", "-profile:v", "high", "-level", "4.1",
                "-b:v", VIDEO_BITRATE, "-rc:v", "vbr", "-tune:v", "hq",
                "-qmin", "10", "-qmax", "32", "-crf", "16",
                # "-t", "10",
                new_filename
            ], stdout=subprocess.PIPE)
        else:
            print("[+]Use Nvidia NvEnc Acceleration")
            encode_process = subprocess.Popen([
                FFMPEG_EXEC, "-hide_banner", "-progress", "-", "-v", "0", "-y",
                "-hwaccel", "cuvid", "-i", orig_filename, "-vf",
                ",".join("subtitles=%s" % i for i in subtitles) + ",hwupload_cuda",
                "-c:a", "copy", "-c:v", "h264_nvenc",
                "-f", "mp4", "-preset:v", "fast", "-profile:v", "high", "-level", "4.1",
                "-b:v", VIDEO_BITRATE, "-rc:v", "vbr", "-tune:v", "hq",
                "-qmin", "10", "-qmax", "32", "-crf", "16",
                # "-t", "10",
                new_filename
            ], stdout=subprocess.PIPE)
    else:
        print("[+]Use CPU Encode")
        encode_process = subprocess.Popen([
            FFMPEG_EXEC, "-hide_banner", "-progress", "-", "-v", "0", "-y",
            "-i", orig_filename, "-vf",
            ",".join("subtitles=%s" % i for i in subtitles),
            "-c:a", "copy", "-c:v", "h264",
            "-f", "mp4", "-preset:v", "fast", "-profile:v", "high", "-level", "4.1",
            "-b:v", VIDEO_BITRATE, "-rc:v", "vbr",
            "-qmin", "10", "-qmax", "32", "-crf", "16",
            # "-t", "10",
            new_filename
        ], stdout=subprocess.PIPE)
    handle_ffmpeg_output(encode_process.stdout)
    return encode_process.wait()


def handle_ffmpeg_output(stderr: IO[bytes]) -> str:
    out_time = "0:0:0.0"
    while True:
        line = stderr.readline()
        if line == b"":
            break
        if line.strip() == b"progress=end":
            # 处理完毕
            break
        if line.startswith(b"out_time="):
            out_time = line.replace(b"out_time=", b"").decode().strip()
            if not PROD_ENV:
                print("CurTime", out_time)
        if line.startswith(b"speed="):
            speed = line.replace(b"speed=", b"").decode().strip()
            if not PROD_ENV:
                print("Speed", speed)

    return out_time


def duration_str_to_float(duration_str) -> float:
    _duration = datetime.strptime(duration_str, "%H:%M:%S.%f") - datetime(1900, 1, 1)
    return _duration.total_seconds()


def quick_split_video(file):
    if not os.path.isfile(file):
        raise FileNotFoundError(file)
    file_name = os.path.split(file)[-1]
    _create_dt = os.path.splitext(file_name)[0]
    create_dt = datetime.strptime(_create_dt, "%Y%m%d_%H%M")
    _duration_str = get_video_real_duration(file)
    duration = duration_str_to_float(_duration_str)
    current_sec = 0
    while current_sec < duration:
        current_dt = (create_dt + timedelta(seconds=current_sec)).strftime("%Y%m%d_%H%M_")
        print("CUR_DT", current_dt)
        print("BIAS_T", current_sec)
        split_process = subprocess.Popen([
            "ffmpeg", "-y", "-hide_banner", "-progress", "-", "-v", "0",
            "-ss", str(current_sec),
            "-i", file_name, "-c", "copy", "-f", "mp4",
            "-t", str(VIDEO_CLIP_EACH_SEC + VIDEO_CLIP_OVERFLOW_SEC),
            "{}.mp4".format(current_dt)
        ], stdout=subprocess.PIPE)
        handle_ffmpeg_output(split_process.stdout)
        current_sec += VIDEO_CLIP_EACH_SEC