# https://t.me/ZGQinc
# 创建下载列表

import os
from bs4 import BeautifulSoup
from urllib.parse import urljoin, unquote, quote

MIRROR_ROOT_DIR = 'myrient_index_mirror'
BASE_URL = 'https://myrient.erista.me/files/'


def generate_download_lists():
    if not os.path.isdir(MIRROR_ROOT_DIR):
        print(f"错误：找不到指定的镜像根目录 '{MIRROR_ROOT_DIR}'。")
        return

    total_links = []
    print("提取链接...")

    for dirpath, _, filenames in os.walk(MIRROR_ROOT_DIR):
        if 'index.html' in filenames:
            html_file_path = os.path.join(dirpath, 'index.html')
            print(f"  正在处理: {html_file_path}")

            local_links = []

            try:
                with open(html_file_path, 'r', encoding='utf-8') as f:
                    soup = BeautifulSoup(f, 'html.parser')
                    links = soup.select('table#list td.link a')

                    for link in links:
                        href = link.get('href')
                        
                        if href and href != '../' and not href.endswith('/'):
                            relative_dir = os.path.relpath(dirpath, MIRROR_ROOT_DIR)
                            if relative_dir == '.':
                                relative_dir = ''
                            
                            path_components = relative_dir.split(os.path.sep)
                            encoded_path_components = [quote(unquote(part)) for part in path_components]
                            web_path_segment = '/'.join(encoded_path_components)
                            
                            fully_encoded_href = quote(unquote(href))
                            
                            if web_path_segment:
                                full_web_path = f"{web_path_segment}/{fully_encoded_href}"
                            else:
                                full_web_path = fully_encoded_href
                            
                            full_url = urljoin(BASE_URL, full_web_path)
                            local_links.append(full_url)

            except Exception as e:
                print(f"    处理文件时出错 {html_file_path}: {e}")
                continue

            if local_links:
                local_list_path = os.path.join(dirpath, 'download_list.txt')
                with open(local_list_path, 'w', encoding='utf-8') as f:
                    f.write('\n'.join(local_links))
                print(f"    已生成: {local_list_path}")

                total_links.extend(local_links)

    if total_links:
        total_list_path = 'total_download_list.txt'
        with open(total_list_path, 'w', encoding='utf-8') as f:
            f.write('\n'.join(total_links))
            
        print(f"\n处理完成。")
        print(f"共提取 {len(total_links)} 个链接。")
        print(f"总下载列表已保存至: {os.path.abspath(total_list_path)}")
    else:
        print("\n未找到任何可提取的链接。")

if __name__ == '__main__':
    generate_download_lists()