#!/usr/bin/env python3
"""
测试加盟商状态变更和工期进度管理
"""

import json
import os
import sys
from datetime import datetime

# 模拟状态文件路径
STATUS_FILE = "/tmp/franchisee_test_status.json"

def create_test_status_file():
    """创建测试状态文件"""
    test_status = {
        "北京加盟商A": "签约后终止",
        "上海加盟商B": "已签约",
        "广州加盟商C": "再次签约"
    }
    
    with open(STATUS_FILE, 'w') as f:
        json.dump(test_status, f, indent=2)
    
    print(f"✅ 创建测试状态文件: {STATUS_FILE}")
    print(f"   包含 {len(test_status)} 个加盟商状态")
    return test_status

def simulate_status_change():
    """模拟状态变更"""
    print("\n🔧 模拟加盟商状态变更:")
    print("   1. '北京加盟商A' 从 '签约后终止' 变为 '再次签约'")
    print("   2. '上海加盟商B' 从 '已签约' 变为 '签约后终止'")
    print("   3. '广州加盟商C' 从 '再次签约' 变为 '已签约'")
    
    new_status = {
        "北京加盟商A": "再次签约",
        "上海加盟商B": "签约后终止",
        "广州加盟商C": "已签约",
        "深圳加盟商D": "已签约"  # 新增加盟商
    }
    
    return new_status

def detect_changes(old_status, new_status):
    """检测状态变化"""
    changes = {
        "new": [],      # 新加盟商
        "renewed": [],  # 再次签约
        "terminated": [],  # 签约后终止
        "removed": []   # 已移除
    }
    
    # 检测新加盟商
    for franchisee in new_status:
        if franchisee not in old_status:
            changes["new"].append(franchisee)
    
    # 检测已移除的加盟商
    for franchisee in old_status:
        if franchisee not in new_status:
            changes["removed"].append(franchisee)
    
    # 检测状态变化
    for franchisee in new_status:
        if franchisee in old_status:
            old_state = old_status[franchisee]
            new_state = new_status[franchisee]
            
            if old_state != new_state:
                if new_state == "再次签约":
                    changes["renewed"].append(franchisee)
                elif new_state == "签约后终止":
                    changes["terminated"].append(franchisee)
    
    return changes

def simulate_progress_management(changes):
    """模拟工期进度管理"""
    print("\n📊 工期进度管理模拟:")
    
    # 处理再次签约的加盟商（添加到进度表）
    if changes["renewed"]:
        print(f"✅ 需要添加到工期进度表的加盟商 ({len(changes['renewed'])} 个):")
        for franchisee in changes["renewed"]:
            print(f"   - {franchisee}: 创建新的工期进度记录")
            print(f"     项目阶段: 重新签约阶段")
            print(f"     计划开始时间: {datetime.now().strftime('%Y-%m-%d')}")
            print(f"     当前进度: 0%")
    
    # 处理签约后终止的加盟商（从进度表删除）
    if changes["terminated"]:
        print(f"❌ 需要从工期进度表删除的加盟商 ({len(changes['terminated'])} 个):")
        for franchisee in changes["terminated"]:
            print(f"   - {franchisee}: 删除工期进度记录")
    
    # 处理新加盟商（添加到进度表）
    if changes["new"]:
        print(f"🆕 新加盟商需要添加到工期进度表 ({len(changes['new'])} 个):")
        for franchisee in changes["new"]:
            print(f"   - {franchisee}: 创建初始工期进度记录")
            print(f"     项目阶段: 初始签约阶段")
            print(f"     计划开始时间: {datetime.now().strftime('%Y-%m-%d')}")
            print(f"     当前进度: 10%")

def test_wecom_cli_integration():
    """测试 WeCom CLI 集成"""
    print("\n🔗 测试 WeCom CLI 集成:")
    
    # 检查 wecom-cli 是否安装
    try:
        import subprocess
        result = subprocess.run(["which", "wecom-cli"], capture_output=True, text=True)
        if result.returncode == 0:
            print(f"✅ wecom-cli 已安装: {result.stdout.strip()}")
            
            # 检查版本
            version_result = subprocess.run(["wecom-cli", "--version"], capture_output=True, text=True)
            if version_result.returncode == 0:
                print(f"   版本: {version_result.stdout.strip()}")
            else:
                print(f"   无法获取版本信息")
        else:
            print("❌ wecom-cli 未安装")
    except Exception as e:
        print(f"❌ 检查 wecom-cli 时出错: {e}")

def main():
    """主测试函数"""
    print("=" * 60)
    print("加盟商状态变更和工期进度管理测试")
    print("=" * 60)
    
    # 1. 创建测试状态文件
    old_status = create_test_status_file()
    
    # 2. 模拟状态变更
    new_status = simulate_status_change()
    
    # 3. 检测状态变化
    changes = detect_changes(old_status, new_status)
    
    # 4. 输出变化统计
    print("\n📈 状态变化检测结果:")
    print(f"   新加盟商: {len(changes['new'])} 个")
    if changes["new"]:
        print(f"     {', '.join(changes['new'])}")
    
    print(f"   再次签约: {len(changes['renewed'])} 个")
    if changes["renewed"]:
        print(f"     {', '.join(changes['renewed'])}")
    
    print(f"   签约后终止: {len(changes['terminated'])} 个")
    if changes["terminated"]:
        print(f"     {', '.join(changes['terminated'])}")
    
    print(f"   已移除: {len(changes['removed'])} 个")
    if changes["removed"]:
        print(f"     {', '.join(changes['removed'])}")
    
    # 5. 模拟工期进度管理
    simulate_progress_management(changes)
    
    # 6. 测试 WeCom CLI 集成
    test_wecom_cli_integration()
    
    # 7. 保存新状态
    with open(STATUS_FILE, 'w') as f:
        json.dump(new_status, f, indent=2)
    print(f"\n💾 已保存新状态到: {STATUS_FILE}")
    
    print("\n" + "=" * 60)
    print("测试完成！")
    print("=" * 60)
    
    # 输出下一步建议
    print("\n🚀 下一步建议:")
    print("1. 初始化 wecom-cli: wecom-cli init")
    print("2. 配置企业微信机器人凭证")
    print("3. 测试实际数据获取: wecom-cli smartsheet get_records '{\"docid\": \"...\", \"sheet_id\": \"...\"}'")
    print("4. 设置定时任务: openclaw cron add '加盟商同步' '*/5 * * * *' 'python3 franchisee_sync_complete.py'")

if __name__ == "__main__":
    main()