"""
测试 Cookie 文件路径支持
"""
import subprocess
import sys
import json


def test_cookie_file_param():
    """测试 --cookies 参数支持文件路径"""
    
    print("="*60)
    print("测试 Cookie 文件路径参数支持")
    print("="*60)
    print()
    
    # 测试命令
    cmd = [
        sys.executable,
        "xhs_publish.py",
        "--cookies", "test_cookies.json",  # 使用文件路径
        "--title", "【测试】Cookie文件路径参数",
        "--content", "测试使用 --cookies 参数传递文件路径，而不是 JSON 字符串",
        "--images", '["https://picsum.photos/800/600","https://picsum.photos/800/600"]',
        "--tags", '["测试","Cookie文件","自动化"]'
    ]
    
    print("执行命令:")
    print(" ".join(cmd))
    print()
    print("-"*60)
    print()
    
    # 执行命令
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            encoding='utf-8'
        )
        
        # 输出结果
        print("标准输出:")
        print(result.stdout)
        
        if result.stderr:
            print("\n标准错误:")
            print(result.stderr)
        
        print()
        print("-"*60)
        
        # 解析结果
        try:
            # 尝试从输出中提取 JSON 结果
            lines = result.stdout.strip().split('\n')
            for i, line in enumerate(lines):
                if line.strip().startswith('{'):
                    json_str = '\n'.join(lines[i:])
                    response = json.loads(json_str)
                    
                    print("\n解析结果:")
                    print(json.dumps(response, ensure_ascii=False, indent=2))
                    
                    if response.get('success'):
                        print("\n✅ 测试成功！Cookie 文件路径参数工作正常")
                        if 'url' in response:
                            print(f"📎 笔记链接: {response['url']}")
                    else:
                        print(f"\n❌ 测试失败: {response.get('error')}")
                    break
        except json.JSONDecodeError:
            print("⚠️ 无法解析 JSON 输出")
        
        return result.returncode == 0
        
    except Exception as e:
        print(f"❌ 执行失败: {str(e)}")
        return False


def test_quick_publish():
    """测试 quick_publish.py 脚本"""
    
    print("\n")
    print("="*60)
    print("测试 quick_publish.py 脚本")
    print("="*60)
    print()
    
    cmd = [
        sys.executable,
        "quick_publish.py",
        "【测试】快速发布脚本",
        "测试 quick_publish.py 的简化调用方式",
        "https://picsum.photos/800/600,https://picsum.photos/800/600",
        "测试,快速发布,自动化",
        "test_cookies.json"
    ]
    
    print("执行命令:")
    print(" ".join(cmd))
    print()
    print("-"*60)
    print()
    
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            encoding='utf-8'
        )
        
        print(result.stdout)
        
        if result.stderr:
            print("\n标准错误:")
            print(result.stderr)
        
        return result.returncode == 0
        
    except Exception as e:
        print(f"❌ 执行失败: {str(e)}")
        return False


if __name__ == "__main__":
    print()
    print("🧪 Cookie 文件路径支持测试")
    print()
    
    # 检查 Cookie 文件是否存在
    import os
    if not os.path.exists('test_cookies.json'):
        print("❌ 错误: test_cookies.json 文件不存在")
        print("请先创建 Cookie 文件")
        sys.exit(1)
    
    print("✅ 找到 Cookie 文件: test_cookies.json")
    print()
    
    # 测试1: xhs_publish.py 使用文件路径
    success1 = test_cookie_file_param()
    
    # 测试2: quick_publish.py
    success2 = test_quick_publish()
    
    # 总结
    print()
    print("="*60)
    print("测试总结")
    print("="*60)
    print(f"xhs_publish.py (Cookie文件): {'✅ 通过' if success1 else '❌ 失败'}")
    print(f"quick_publish.py:           {'✅ 通过' if success2 else '❌ 失败'}")
    print()
    
    if success1 and success2:
        print("🎉 所有测试通过！")
    else:
        print("⚠️ 部分测试失败，请检查错误信息")
