import os
import subprocess
import threading
import asyncio
import uuid
import time
import signal
import sys
import shutil
import logging
import spider
import stream

# ----------------- Logging Setup -----------------
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    datefmt="%H:%M:%S"
)

# ----------------- Low-Latency Douyin to YouTube Streamer -----------------
class DouyinToYouTubeStreamer:
    def __init__(self, bitrate=5000, audio_bitrate=128, resolution='720x1280', fps=30, gop=60):
        self.proc = None
        self.stop_flag = threading.Event()
        self.bitrate = bitrate
        self.audio_bitrate = audio_bitrate
        self.resolution = resolution
        self.fps = fps
        self.gop = gop
        self.start_time = None
        self.room_name = None
        self.semaphore = threading.Semaphore(1)
        self.pushing = False  # 是否正在推流

    def start_stream(self, real_url, youtube_key, room_name=None):
        self.room_name = room_name or f"抖音_{str(uuid.uuid4())[:8]}"
        logging.info(f"[{self.room_name}] 启动低延迟推流，目标 YouTube Key: {youtube_key}")
        threading.Thread(target=self._run_ffmpeg_loop, args=(real_url, youtube_key), daemon=True).start()
        threading.Thread(target=self._monitor_thread, daemon=True).start()

    def _build_ffmpeg_cmd(self, real_url, youtube_key):
        user_agent = ("Mozilla/5.0 (Linux; Android 11; SAMSUNG SM-G973U) AppleWebKit/537.36 "
                      "(KHTML, like Gecko) SamsungBrowser/14.2 Chrome/87.0.4280.141 Mobile Safari/537.36")
        headers = "Referer: https://www.douyin.com/\r\nOrigin: https://www.douyin.com\r\n"

        cmd = [
            'ffmpeg', '-y', '-v', 'error', '-hide_banner',
            '-rw_timeout', '10000000',
            '-analyzeduration', '1000000',
            '-probesize', '5000000',
            '-thread_queue_size', '512',
            '-user_agent', user_agent,
            '-headers', headers,
            '-protocol_whitelist', 'file,pipe,http,https,tcp,tls,udp,rtp,crypto',
            '-fflags', '+discardcorrupt+genpts',
            '-flags', 'low_delay',
            '-http_seekable', '0',
            '-avioflags', 'direct',
            '-reconnect', '1',
            '-reconnect_at_eof', '1',
            '-reconnect_streamed', '1',
            '-reconnect_delay_max', '5',
            '-flush_packets', '1',
            '-i', real_url,
            '-c:v', 'libx264',
            '-preset', 'veryfast',
            '-tune', 'zerolatency',
            '-crf', '23',
            '-pix_fmt', 'yuv420p',
            '-profile:v', 'main',
            '-level', '3.1',
            '-x264-params', f'keyint={self.gop}:scenecut=0:min-keyint={self.gop//2}',
            '-g', str(self.gop),
            '-r', str(self.fps),
            '-s', self.resolution,
            '-b:v', f'{self.bitrate}k',
            '-maxrate', f'{self.bitrate}k',
            '-bufsize', f'{self.bitrate * 2}k',
            '-c:a', 'aac',
            '-b:a', f'{self.audio_bitrate}k',
            '-ar', '44100',
            '-ac', '2',
            '-strict', '-2',
            '-avoid_negative_ts', 'make_zero',
            '-f', 'flv',
            f'rtmp://a.rtmp.youtube.com/live2/{youtube_key}'
        ]
        return cmd

    def _run_ffmpeg_loop(self, real_url, youtube_key):
        while not self.stop_flag.is_set():
            try:
                with self.semaphore:
                    cmd = self._build_ffmpeg_cmd(real_url, youtube_key)
                    self.proc = subprocess.Popen(
                        cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE,
                        bufsize=0, universal_newlines=False
                    )
                    self.start_time = time.time()
                    self.pushing = False
                    logging.info(f"[{self.room_name}] FFmpeg 启动成功 (PID: {self.proc.pid})")

                    def read_stderr():
                        try:
                            for line in iter(self.proc.stderr.readline, b''):
                                if self.stop_flag.is_set():
                                    break
                                if line:
                                    decoded = line.decode('utf-8', errors='ignore').strip()
                                    logging.info(f"[{self.room_name} FFmpeg]: {decoded}")
                                    # 判断推流是否成功
                                    if not self.pushing and "frame=" in decoded and "fps=" in decoded:
                                        self.pushing = True
                                        logging.info(f"[{self.room_name}] 推流到 YouTube 成功")
                        except Exception as e:
                            logging.error(f"[{self.room_name}] stderr线程异常: {e}")

                    stderr_thread = threading.Thread(target=read_stderr, daemon=True)
                    stderr_thread.start()

                    self.proc.wait()
                    if not self.stop_flag.is_set():
                        logging.warning(f"[{self.room_name}] FFmpeg 退出 (返回码: {self.proc.returncode})，1秒后重启...")
                        self.pushing = False
            except Exception as e:
                logging.error(f"[{self.room_name}] FFmpeg 启动异常: {e}")
            finally:
                if self.proc and self.proc.poll() is None:
                    self.proc.terminate()
                    try:
                        self.proc.wait(timeout=1)
                    except subprocess.TimeoutExpired:
                        self.proc.kill()
                self.proc = None
                if not self.stop_flag.is_set():
                    time.sleep(1)

    def _monitor_thread(self):
        term_width, _ = shutil.get_terminal_size()
        bar_width = min(50, term_width - 30)
        while not self.stop_flag.is_set():
            if self.proc:
                uptime = time.time() - self.start_time if self.start_time else 0
                uptime_str = f"{int(uptime // 60):02d}:{int(uptime % 60):02d}"
                status = "推流中" if self.pushing else "启动中"
                bar_len = bar_width if self.pushing else 0
                bar = "#" * bar_len + "-" * (bar_width - bar_len)
                print(f"\r[{self.room_name}] [{bar}] {status} | 运行时间: {uptime_str} | 码率: {self.bitrate}k", end="")
            else:
                print(f"\r[{self.room_name}] FFmpeg 未运行", end="")
            time.sleep(2)

    def stop(self):
        logging.info(f"[{self.room_name}] 停止推流...")
        self.stop_flag.set()
        if self.proc and self.proc.poll() is None:
            self.proc.terminate()
            try:
                self.proc.wait(timeout=1)
            except subprocess.TimeoutExpired:
                self.proc.kill()


# ----------------- Douyin Stream Parsing -----------------
async def get_douyin_real_url(record_url, record_quality="原画", proxy_addr=None, cookies=''):
    try:
        if 'v.douyin.com' not in record_url and '/user/' not in record_url:
            json_data = await spider.get_douyin_stream_data(url=record_url, proxy_addr=proxy_addr, cookies=cookies)
        else:
            json_data = await spider.get_douyin_app_stream_data(url=record_url, proxy_addr=proxy_addr, cookies=cookies)
        port_info = await stream.get_douyin_stream_url(json_data, record_quality, proxy_addr)
        return port_info.get("record_url")
    except Exception as e:
        logging.error(f"获取抖音真实流失败: {e}")
        return None

def start_douyin_to_youtube(record_url, youtube_key, room_name=None, proxy_addr=None, cookies='', bitrate=5000):
    real_url = asyncio.run(get_douyin_real_url(record_url, proxy_addr, cookies))
    if not real_url:
        logging.error("获取真实直播流失败")
        return None
    logging.info(f"实际直播流: {real_url}")
    streamer = DouyinToYouTubeStreamer(bitrate=bitrate)
    streamer.start_stream(real_url, youtube_key, room_name)
    return streamer


# ----------------- Main Program -----------------
if __name__ == "__main__":
    DOUYIN_URL = "https://live.douyin.com/112633436109"
    YOUTUBE_KEY = "qxvb-r47b-r5ju-6ud3-6k7z"

    hls_instance = start_douyin_to_youtube(DOUYIN_URL, YOUTUBE_KEY)
    if not hls_instance:
        logging.error("推流实例创建失败，程序退出")
        sys.exit(1)

    def signal_handler(sig, frame):
        if hls_instance:
            hls_instance.stop()
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    logging.info("程序已启动，低延迟推流中，按 Ctrl+C 停止...")
    while True:
        time.sleep(60)
