import os
import sys
import time
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

# === 处理命令行参数 ===
if len(sys.argv) < 2:
    print("❌ 缺少参数！请使用命令运行：")
    print("   python script.py <目标URL>")
    sys.exit(1)

BASE_URL = sys.argv[1]  # 从命令行获取URL
HREFS_FILE = 'hrefs.txt'
RESULT_FILE = 'audio_results.txt'
DOWNLOAD_DIR = 'downloaded_audio'

# 配置浏览器
chrome_options = Options()
chrome_options.add_argument("--headless")  # 无界面模式
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")

# 启动 Chrome 浏览器
driver = webdriver.Chrome(options=chrome_options)


# === 1. 获取 href 链接 ===
def fetch_hrefs():
    print(f"🔍 访问 {BASE_URL}，提取音频页面链接...")
    driver.get(BASE_URL)
    time.sleep(5)  # 等待页面加载

    name_divs = driver.find_elements(By.CLASS_NAME, 'name')
    href_list = []

    for div in name_divs:
        try:
            a_tag = div.find_element(By.TAG_NAME, 'a')
            href = a_tag.get_attribute('href')
            if href:
                href_list.append(href)
        except Exception:
            continue

    # 存入 hrefs.txt
    with open(HREFS_FILE, 'w', encoding='utf-8') as file:
        for href in href_list:
            file.write(href + '\n')

    print(f"✅ 提取 {len(href_list)} 个音频页面链接，已存入 {HREFS_FILE}")
    return href_list


# === 2. 下载 MP3 ===
def download_mp3(urls):
    if not os.path.exists(DOWNLOAD_DIR):
        os.makedirs(DOWNLOAD_DIR)

    results = []

    for url in urls:
        url = url.strip()
        if not url:
            continue

        try:
            print(f"🚀 访问 {url}，获取音频信息...")
            driver.get(url)
            time.sleep(3)

            # 获取 MP3 资源链接
            audio_element = driver.find_element(By.XPATH, '//audio[@id="jp_audio_0"]')
            audio_src = audio_element.get_attribute('src')

            # 获取音频标题
            title_element = driver.find_element(By.XPATH, '//div[@class="djname lkpc" and @id="player_title"]')
            audio_title = title_element.text.strip()

            # 处理文件名（去掉特殊字符）
            safe_title = "".join(c for c in audio_title if c.isalnum() or c in " _-").strip()
            filename = f"{safe_title}.mp3"
            file_path = os.path.join(DOWNLOAD_DIR, filename)

            # 下载 MP3 文件
            response = requests.get(audio_src, stream=True)
            if response.status_code == 200:
                with open(file_path, 'wb') as mp3_file:
                    for chunk in response.iter_content(1024):
                        mp3_file.write(chunk)
                result = f"✅ 成功：{url}\n标题：{audio_title}\n音频下载完成：{file_path}\n"
            else:
                result = f"⚠️ 下载失败：{audio_title} ({audio_src})\n"

            print(result)
            results.append(result)

        except Exception as e:
            result = f"⚠️ 处理 {url} 时出错：{e}\n"
            print(result)
            results.append(result)

    # 记录下载结果
    with open(RESULT_FILE, 'w', encoding='utf-8') as file:
        for result in results:
            file.write(result + '\n')

    print(f"🎉 处理完成，结果已保存在 {RESULT_FILE}，所有 MP3 已下载到 '{DOWNLOAD_DIR}' 目录。")


# === 主执行逻辑 ===
hrefs = fetch_hrefs()
if hrefs:
    download_mp3(hrefs)
else:
    print("❌ 没有找到任何音频页面，程序终止！")

# 关闭浏览器
driver.quit()
