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

from config import FFMPEG_EXEC, VIDEO_BITRATE, FFMPEG_USE_NVIDIA_GPU, VIDEO_CLIP_EACH_SEC, VIDEO_CLIP_OVERFLOW_SEC, \
    FFMPEG_USE_INTEL_GPU, VIDEO_OUTPUT_DIR


def base_ts_to_filename(start_ts: float, is_mp4=False) -> str:
    base_start = datetime.fromtimestamp(start_ts)
    if is_mp4:
        return base_start.strftime("%Y%m%d_%H%M.mp4")
    else:
        return base_start.strftime("%Y%m%d_%H%M.flv")


def get_video_real_duration(filename):
    ffmpeg_process = subprocess.Popen([
        FFMPEG_EXEC, *_common_ffmpeg_setting(), "-i", filename, "-c", "copy", "-f", "null", "-"
    ], stdout=subprocess.PIPE)
    return handle_ffmpeg_output(ffmpeg_process.stdout)


def multi_gpu_encode_video_with_subtitles(orig_filename: str, subtitles: list[str], base_ts: float):
    _duration_str = get_video_real_duration(orig_filename)
    duration = duration_str_to_float(_duration_str)
    current_sec = 0
    while current_sec < duration:
        if (current_sec + VIDEO_CLIP_OVERFLOW_SEC * 2) > duration:
            print("[-]Less than 2 overflow sec, skip")
            break
        new_filename = base_ts_to_filename(base_ts + current_sec, True)
        new_fullpath = os.path.join(VIDEO_OUTPUT_DIR, new_filename)
        print("CUR_FN", new_filename, "BIAS_T", current_sec)
        if FFMPEG_USE_NVIDIA_GPU:
            process = get_encode_process_use_nvenc(orig_filename, subtitles, new_fullpath,
                                                   current_sec, VIDEO_CLIP_EACH_SEC + VIDEO_CLIP_OVERFLOW_SEC)
        elif FFMPEG_USE_INTEL_GPU:
            process = get_encode_process_use_intel(orig_filename, subtitles, new_fullpath,
                                                   current_sec, VIDEO_CLIP_EACH_SEC + VIDEO_CLIP_OVERFLOW_SEC)
        else:
            process = get_encode_process_use_cpu(orig_filename, subtitles, new_fullpath,
                                                 current_sec, VIDEO_CLIP_EACH_SEC + VIDEO_CLIP_OVERFLOW_SEC)
        handle_ffmpeg_output(process.stdout)
        process.wait()
        current_sec += VIDEO_CLIP_EACH_SEC


def get_encode_process_use_nvenc(orig_filename: str, subtitles: list[str], new_filename: str,
                                 skip: float = 0, duration: float = 0):
    print("[+]Use Nvidia NvEnc Acceleration")
    encode_process = subprocess.Popen([
        FFMPEG_EXEC, *_common_ffmpeg_setting(),
        "-ss", str(skip), "-copyts", "-t", str(duration),
        "-i", orig_filename, "-vf",
        ",".join("subtitles=%s" % i for i in subtitles) + ",hwupload_cuda",
        "-ss", str(skip),
        "-c:a", "copy", "-c:v", "h264_nvenc",
        "-f", "mp4", "-b:v", VIDEO_BITRATE, "-rc:v", "vbr", "-tune:v", "hq",
        *_common_ffmpeg_params(),
        # "-t", "10",
        new_filename
    ], stdout=subprocess.PIPE)
    return encode_process


def get_encode_process_use_intel(orig_filename: str, subtitles: list[str], new_filename: str,
                                 skip: float = 0, duration: float = 0):
    if platform.system().lower() == "windows":
        print("[+]Use Intel QSV Acceleration")
        encode_process = subprocess.Popen([
            FFMPEG_EXEC, *_common_ffmpeg_setting(),
            "-ss", str(skip), "-copyts", "-t", str(duration),
            "-hwaccel", "qsv", "-i", orig_filename, "-vf",
            ",".join("subtitles=%s" % i for i in subtitles),
            "-ss", str(skip),
            "-c:a", "copy", "-c:v", "h264_qsv",
            "-f", "mp4", "-b:v", VIDEO_BITRATE, "-rc:v", "vbr", "-tune:v", "hq",
            *_common_ffmpeg_params(),
            # "-t", "10",
            new_filename
        ], stdout=subprocess.PIPE)
    else:
        print("[+]Use Intel VAAPI Acceleration")
        encode_process = subprocess.Popen([
            FFMPEG_EXEC, *_common_ffmpeg_setting(),
            "-ss", str(skip), "-copyts", "-t", str(duration),
            "-hwaccel", "vaapi", "-i", orig_filename, "-vf",
            ",".join("subtitles=%s" % i for i in subtitles) + ",hwupload",
            "-ss", str(skip),
            "-c:a", "copy", "-c:v", "h264_vaapi",
            "-f", "mp4", "-b:v", VIDEO_BITRATE, "-rc:v", "vbr", "-tune:v", "hq",
            *_common_ffmpeg_params(),
            # "-t", "10",
            new_filename
        ], stdout=subprocess.PIPE)
    return encode_process


def get_encode_process_use_cpu(orig_filename: str, subtitles: list[str], new_filename: str,
                               skip: float = 0, duration: float = 0):
    print("[+]Use CPU Encode")
    encode_process = subprocess.Popen([
        FFMPEG_EXEC, *_common_ffmpeg_setting(),
        "-ss", str(skip), "-copyts", "-t", str(duration),
        "-i", orig_filename, "-vf",
        ",".join("subtitles=%s" % i for i in subtitles),
        "-ss", str(skip),
        "-c:a", "copy", "-c:v", "h264",
        "-f", "mp4", "-b:v", VIDEO_BITRATE,
        *_common_ffmpeg_params(),
        # "-t", "10",
        new_filename
    ], stdout=subprocess.PIPE)
    return encode_process


def handle_ffmpeg_output(stdout: IO[bytes]) -> str:
    out_time = "0:0:0.0"
    speed = "0"
    if stdout is None:
        print("[!]STDOUT is null")
        return out_time
    _i = 0
    while True:
        line = stdout.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 line.startswith(b"speed="):
            speed = line.replace(b"speed=", b"").decode().strip()
            _i += 1
    print("[ ]Speed:", out_time, "@", 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:
        if (current_sec + VIDEO_CLIP_OVERFLOW_SEC * 2) > duration:
            print("[-]Less than 2 overflow sec, skip")
            break
        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_EXEC, *_common_ffmpeg_setting(),
            "-ss", str(current_sec),
            "-i", file, "-c", "copy", "-f", "mp4",
            "-t", str(VIDEO_CLIP_EACH_SEC + VIDEO_CLIP_OVERFLOW_SEC),
            "-fflags", "+genpts", "-shortest", "-movflags", "faststart",
            "{}.mp4".format(current_dt)
        ], stdout=subprocess.PIPE)
        handle_ffmpeg_output(split_process.stdout)
        split_process.wait()
        current_sec += VIDEO_CLIP_EACH_SEC


def _common_ffmpeg_setting():
    return (
        "-y", "-hide_banner", "-progress", "-", "-loglevel", "error"
    )


def _common_ffmpeg_params():
    return (
        "-f", "mp4", "-b:v", VIDEO_BITRATE, "-c:a", "copy",
        "-sub_charenc", "UTF-8",
        "-preset:v", "fast", "-profile:v", "main",
        "-qmin", "12", "-qmax", "34", "-crf", "24", "-tune:v", "animation",
        "-fflags", "+genpts", "-shortest", "-movflags", "faststart"
    )