# -*- coding: utf-8 -*-
import os
import re
import json
import requests
import logging
from tqdm import tqdm
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor

# 设置日志
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}

# 获取视频信息（函数名不变）
def get_video_info(video_url):
    logging.info(f"解析视频链接: {video_url}")
    
    try:
        response = requests.get(video_url, headers=HEADERS, timeout=10)
        response.raise_for_status()
    except requests.RequestException as e:
        logging.error(f"请求失败: {e}")
        return None
    
    # 解析 HTML
    soup = BeautifulSoup(response.text, "html.parser")
    script_tag = soup.find("script", text=re.compile("window.__INIT_PROPS__"))
    
    if not script_tag:
        logging.error("未找到视频数据")
        return None

    match = re.search(r'window\.__INIT_PROPS__\s?=\s?({.*?});', script_tag.string)
    if not match:
        logging.error("JSON 数据提取失败")
        return None
    
    try:
        video_json = json.loads(match.group(1))
        video_data = video_json.get("/video/", {}).get("video", {})
        video_url = video_data.get("playAddr")
        title = video_data.get("title", "douyin_video")

        if not video_url:
            logging.error("未找到视频地址")
            return None
        
        return {"url": video_url, "title": title}
    
    except json.JSONDecodeError:
        logging.error("解析 JSON 失败")
        return None

# 下载视频（函数名不变）
def download_video(video_url, save_path):
    logging.info(f"开始下载: {video_url}")

    try:
        response = requests.get(video_url, stream=True, headers=HEADERS, timeout=10)
        response.raise_for_status()
    except requests.RequestException as e:
        logging.error(f"下载失败: {e}")
        return
    
    total_size = int(response.headers.get("content-length", 0))
    
    with open(save_path, "wb") as file, tqdm(
        desc="下载进度",
        total=total_size,
        unit="B",
        unit_scale=True,
        unit_divisor=1024
    ) as bar:
        for chunk in response.iter_content(chunk_size=1024):
            if chunk:
                file.write(chunk)
                bar.update(len(chunk))

    logging.info(f"下载完成: {save_path}")

# 批量下载（函数名不变）
def batch_download(urls, output_dir):
    os.makedirs(output_dir, exist_ok=True)
    
    with ThreadPoolExecutor(max_workers=3) as executor:
        futures = []
        for url in urls:
            video_info = get_video_info(url)
            if video_info:
                filename = f"{video_info['title']}.mp4"
                save_path = os.path.join(output_dir, filename)
                futures.append(executor.submit(download_video, video_info["url"], save_path))

        for future in futures:
            future.result()  # 确保所有任务完成