import requests
import os
import shutil
import zipfile
import time
from tqdm import tqdm
from colorama import Fore, Style, init

# 初始化彩色输出支持
init(autoreset=True)

def print_header():
    """打印标题横幅"""
    header = "📦 美化配置（下载+解压+移动+清理）"
    border = "=" * (len(header) + 4)
    print(f"\n{Fore.CYAN}{border}")
    print(f"{Fore.CYAN}  {header}  ")
    print(f"{Fore.CYAN}{border}{Style.RESET_ALL}\n")

def step_indicator(step_num, total_steps, text):
    """步骤指示器（带进度感）"""
    progress = f"[{step_num}/{total_steps}]"
    print(f"\n{Fore.MAGENTA}{'='*10} {progress} {text} {'='*10}{Style.RESET_ALL}")

def typewriter_effect(text, speed=0.03, color=Fore.WHITE):
    """打字机效果文字输出（支持自定义颜色）"""
    for char in text:
        print(f"{color}{char}", end='', flush=True)
        time.sleep(speed)
    print(f"{Style.RESET_ALL}")

def check_and_create_dir(save_path):
    """检查并创建目录（带流程反馈）"""
    step_indicator(1, 6, "检查保存路径")
    try:
        if not os.path.exists(save_path):
            typewriter_effect(f"路径不存在，正在创建目录...", 0.02, Fore.YELLOW)
            for i in range(3):
                print(f"{Fore.CYAN}· 处理中{i+1}...", end='\r')
                time.sleep(0.5)
            os.makedirs(save_path, exist_ok=True)
            print(f"\n{Fore.GREEN}✅ 目录创建成功：{save_path}")
        else:
            typewriter_effect(f"✓ 保存路径已就绪：{save_path}", 0.02, Fore.BLUE)
        return True
    except Exception as e:
        print(f"{Fore.RED}❌ 路径处理失败：{str(e)}")
        return False

def connect_to_server(url):
    """获取下载地址（带动态反馈）"""
    step_indicator(2, 6, "验证下载地址")
    try:
        typewriter_effect(f"📡 正在获取地址...", 0.02, Fore.CYAN)
        for _ in range(5):
            print(f"{Fore.YELLOW}→ 建立连接中{'.'*_}", end='\r')
            time.sleep(0.3)
        response = requests.head(url, allow_redirects=True, timeout=10)
        response.raise_for_status()
        print(f"\n{Fore.GREEN}✅ 地址获取成功")
        return True
    except Exception as e:
        print(f"\n{Fore.RED}❌ 地址获取失败：{str(e)}")
        return False

def get_file_info(url):
    """获取文件信息（大小等）"""
    step_indicator(3, 6, "获取文件信息")
    try:
        response = requests.get(url, stream=True, timeout=10)
        file_size = int(response.headers.get('content-length', 0))
        print(f"{Fore.MAGENTA}📊 文件信息：")
        print(f"   大小：{file_size / (1024*1024):.2f} MB")
        print(f"   类型：压缩包文件")
        return response, file_size
    except Exception as e:
        print(f"{Fore.RED}❌ 获取文件信息失败：{str(e)}")
        return None, 0

def download_with_style(url, save_path, filename):
    """带流程感的下载主函数"""
    full_path = os.path.join(save_path, filename)
    
    if not check_and_create_dir(save_path) or not connect_to_server(url):
        return None
    
    response, file_size = get_file_info(url)
    if not response:
        return None
    
    step_indicator(4, 6, "正在下载文件")
    print(f"{Fore.GREEN}🚀 准备开始下载...{Style.RESET_ALL}")
    time.sleep(1)
    
    try:
        with open(full_path, 'wb') as f, tqdm(
            total=file_size,
            unit='B',
            unit_scale=True,
            unit_divisor=1024,
            bar_format=f"{Fore.CYAN}{{l_bar}}{{bar}}| {Fore.YELLOW}{{n_fmt}}/{{total_fmt}} {Fore.MAGENTA}[速度: {{rate_fmt}}]{{postfix}}{Style.RESET_ALL}"
        ) as pbar:
            pbar.set_description("下载进度")
            for chunk in response.iter_content(chunk_size=1024):
                if chunk:
                    f.write(chunk)
                    pbar.update(len(chunk))
        
        print("\n" + "="*50)
        typewriter_effect(f"🎉 下载完成！文件已保存至：", 0.05, Fore.GREEN)
        print(f"{Fore.CYAN}{full_path}")
        print("="*50 + Style.RESET_ALL)
        return full_path
    except Exception as e:
        print(f"\n{Fore.RED}❌ 下载过程出错：{str(e)}{Style.RESET_ALL}")
        if os.path.exists(full_path):
            os.remove(full_path)
        return None

def extract_and_move_folders(zip_path, terminal_target_dir):
    """解压zip并移动文件夹到终端（带流程反馈）"""
    step_indicator(5, 6, "解压并移动到终端")
    temp_extract_dir = "/data/data/com.termux/files/home/临时解压目录/"
    
    try:
        if not zipfile.is_zipfile(zip_path):
            print(f"{Fore.RED}❌ {zip_path} 不是有效的zip文件")
            return False
        
        if os.path.exists(temp_extract_dir):
            shutil.rmtree(temp_extract_dir)
        os.makedirs(temp_extract_dir)
        typewriter_effect(f"🔓 正在解压压缩包...", 0.02, Fore.YELLOW)
        
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            top_folders = set()
            for item in zip_ref.namelist():
                if item.endswith('/'):
                    top_folders.add(item.split('/')[0])
            top_folders = list(top_folders)
            
            if not top_folders:
                print(f"{Fore.RED}❌ zip文件中未找到任何文件夹")
                return False
            
            typewriter_effect(f"📂 压缩包内包含 {len(top_folders)} 个文件夹：", 0.02, Fore.MAGENTA)
            for i, folder in enumerate(top_folders, 1):
                print(f"   {i}. {folder}")
            
            zip_ref.extractall(temp_extract_dir)
        
        if not os.path.exists(terminal_target_dir):
            os.makedirs(terminal_target_dir)
            print(f"\n{Fore.GREEN}✅ 创建终端目录：{terminal_target_dir}")
        
        typewriter_effect(f"🚚 正在将文件夹移动到终端...", 0.02, Fore.CYAN)
        success_count = 0
        for folder in top_folders:
            src = os.path.join(temp_extract_dir, folder)
            dst = os.path.join(terminal_target_dir, folder)
            
            if os.path.exists(dst):
                shutil.rmtree(dst)
                print(f"{Fore.YELLOW}⚠️  已覆盖终端中已存在的 {folder}")
            
            shutil.move(src, dst)
            print(f"{Fore.GREEN}✅ 移动成功：{folder} → {terminal_target_dir}")
            success_count += 1
        
        if success_count == len(top_folders):
            print("\n" + "="*50)
            typewriter_effect(f"🎉 所有文件夹均移动到终端！", 0.05, Fore.GREEN)
            print(f"{Fore.CYAN}📌 终端目录：{terminal_target_dir}")
            print("="*50 + Style.RESET_ALL)
            return True
        else:
            print(f"{Fore.RED}❌ 仅成功移动 {success_count}/{len(top_folders)} 个文件夹")
            return False
    except Exception as e:
        print(f"\n{Fore.RED}❌ 解压/移动失败：{str(e)}")
        return False
    finally:
        if os.path.exists(temp_extract_dir):
            shutil.rmtree(temp_extract_dir)
            print(f"\n{Fore.YELLOW}🗑️  已清理临时解压目录")

def delete_zip_file(zip_path):
    """自动删除下载后的zip文件（最后一步）"""
    step_indicator(6, 6, "清理压缩包文件")
    try:
        if os.path.exists(zip_path):
            os.remove(zip_path)
            typewriter_effect(f"🗑️  已自动删除压缩包：{zip_path}", 0.03, Fore.GREEN)
            return True
        else:
            print(f"{Fore.YELLOW}⚠️  压缩包不存在：{zip_path}（可能已被删除）")
            return False
    except Exception as e:
        print(f"{Fore.RED}❌ 删除压缩包失败：{str(e)}")
        return False

if __name__ == "__main__":
    # 配置信息
    DOWNLOAD_URL = "http://pan.cdndns.site/down/156688d29bcf9bc7ae75baa2543a1d0a"
    SAVE_DIR = "/data/data/com.termux/files/home/"
    FILE_NAME = "败渊.zip"
    TERMINAL_TARGET_DIR = "/data/data/com.termux/files/home/"
    
    # 启动界面
    print_header()
    typewriter_effect("欢迎使用全流程美化工具，即将开始操作...", 0.03, Fore.BLUE)
    typewriter_effect("流程：下载zip → 解压 → 移动文件夹 → 自动删除zip", 0.03)
    time.sleep(1)
    
    # 执行全流程（严格顺序：下载→解压移动→删除zip）
    zip_file_path = download_with_style(DOWNLOAD_URL, SAVE_DIR, FILE_NAME)
    if zip_file_path:
        move_success = extract_and_move_folders(zip_file_path, TERMINAL_TARGET_DIR)
        # 无论移动是否成功，都尝试删除zip（若移动失败，用户可手动重新解压）
        delete_zip_file(zip_file_path)
    
    # 结束提示
    print(f"\n{Fore.BLUE}按回车键退出...{Style.RESET_ALL}")
    input()
