#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import subprocess
import shutil

def run_command(command, shell=False):
    """运行命令并返回结果"""
    try:
        result = subprocess.run(command, shell=shell, check=True, 
                               capture_output=True, text=True)
        return result.returncode, result.stdout, result.stderr
    except subprocess.CalledProcessError as e:
        return e.returncode, e.stdout, e.stderr

def main():
    print("开始设置YOLO项目环境...")
    
    # 检查Python3是否安装
    if not shutil.which("python3"):
        print("错误: Python3 未安装，请先安装Python3")
        sys.exit(1)
    
    # 创建虚拟环境
    print("创建虚拟环境...")
    returncode, stdout, stderr = run_command([sys.executable, "-m", "venv", "venv"])
    if returncode != 0:
        print(f"创建虚拟环境失败: {stderr}")
        sys.exit(1)
    
    # 确定虚拟环境中的Python解释器路径
    if os.name == 'nt':  # Windows
        venv_python = os.path.join("venv", "Scripts", "python.exe")
        venv_pip = os.path.join("venv", "Scripts", "pip.exe")
    else:  # macOS/Linux
        venv_python = os.path.join("venv", "bin", "python")
        venv_pip = os.path.join("venv", "bin", "pip")
    
    # 升级pip
    print("升级pip...")
    returncode, stdout, stderr = run_command([venv_pip, "install", "--upgrade", "pip"])
    if returncode != 0:
        print(f"升级pip失败: {stderr}")
    
    # 安装依赖
    print("安装项目依赖...")
    returncode, stdout, stderr = run_command([venv_pip, "install", "-r", "requirements.txt"])
    if returncode != 0:
        print(f"安装依赖失败: {stderr}")
        sys.exit(1)
    
    # 检查测试视频文件是否存在
    if not os.path.exists("res/test.mp4"):
        print("❌ 错误: res/test.mp4 文件不存在！")
        print()
        print("请按以下步骤操作：")
        print("1. 在 res/ 目录中放置一个视频文件")
        print("2. 将视频文件重命名为 test.mp4")
        print("3. 重新运行此脚本")
        print()
        print("支持的视频格式: .mp4, .avi, .mov, .mkv 等")
        print("脚本已停止运行。")
        sys.exit(1)
    
    # 运行应用
    print("运行应用...")
    os.chdir("src")
    returncode, stdout, stderr = run_command([os.path.join("..", venv_python), "app.py"])
    
    if returncode == 0:
        print("✅ 应用运行完成！检测结果已保存在 runs/detect/ 目录中")
    else:
        print(f"应用运行失败: {stderr}")
        sys.exit(1)

if __name__ == "__main__":
    main() 