#!/usr/bin/env python3
"""
加盟商状态同步 - Cron专用版本
每分钟执行一次，监控加盟商状态变化并同步到工期进度表
"""

import os
import sys
import json
import time
import logging
from datetime import datetime

# 添加Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# 配置信息
CONFIG = {
    "docid": "dcyeOLceOJqbuQpvY_EyivG5xx0cCPcT2x4kZ3UtkVJBhGqrD7wdc_iKB3za3vqq0foQifL-Y2npwGb1bl6Hb9EQ",
    "status_sheet_id": "q979lj",
    "progress_sheet_id": "MAqXdi",
    "status_field": "状态",
    "franchisee_field": "加盟商名称",
    "terminated_status": "签约后终止",
    "renewed_status": "再次签约",
}

# 设置日志
log_file = "/var/log/franchisee_sync.log"
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(log_file),
        logging.StreamHandler()
    ]
)

def log_start():
    """记录任务开始"""
    logging.info("=" * 60)
    logging.info("加盟商状态同步任务开始执行")
    logging.info(f"执行时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    logging.info(f"文档ID: {CONFIG['docid']}")
    logging.info("=" * 60)

def log_end():
    """记录任务结束"""
    logging.info("=" * 60)
    logging.info("加盟商状态同步任务执行完成")
    logging.info(f"完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    logging.info("=" * 60)

def check_status_changes(last_status, current_records):
    """检查状态变化"""
    changes = {"terminated": [], "renewed": []}
    
    for record in current_records:
        franchisee = record.get("加盟商名称")
        status = record.get("状态")
        
        if not franchisee or not status:
            continue
            
        last = last_status.get(franchisee)
        
        # 检查状态变化
        if last != status:
            logging.info(f"状态变化: {franchisee} - {last} -> {status}")
            
            if status == CONFIG["terminated_status"]:
                changes["terminated"].append(franchisee)
            elif status == CONFIG["renewed_status"]:
                changes["renewed"].append(franchisee)
                
        # 更新最后状态
        last_status[franchisee] = status
        
    return changes, last_status

def simulate_get_records():
    """模拟获取记录（实际使用时替换为wecom_mcp调用）"""
    # 模拟数据
    return [
        {"加盟商名称": "北京加盟商A", "状态": "正常", "record_id": "rec1"},
        {"加盟商名称": "上海加盟商B", "状态": "签约后终止", "record_id": "rec2"},
        {"加盟商名称": "广州加盟商C", "状态": "再次签约", "record_id": "rec3"},
    ]

def simulate_sync_operations(changes):
    """模拟同步操作（实际使用时替换为wecom_mcp调用）"""
    if changes["terminated"]:
        logging.info(f"删除终止加盟商的工期进度记录: {', '.join(changes['terminated'])}")
        # 实际调用: wecom_mcp call doc smartsheet_delete_records
        
    if changes["renewed"]:
        logging.info(f"添加再次签约加盟商的工期进度记录: {', '.join(changes['renewed'])}")
        # 实际调用: wecom_mcp call doc smartsheet_add_records

def main():
    """主函数"""
    try:
        log_start()
        
        # 状态跟踪文件
        status_file = "/tmp/franchisee_last_status.json"
        
        # 加载上次状态
        last_status = {}
        if os.path.exists(status_file):
            try:
                with open(status_file, 'r', encoding='utf-8') as f:
                    last_status = json.load(f)
                logging.info(f"加载了 {len(last_status)} 个加盟商的上次状态")
            except Exception as e:
                logging.warning(f"加载状态文件失败: {e}")
        
        # 获取当前记录（模拟）
        current_records = simulate_get_records()
        logging.info(f"获取到 {len(current_records)} 条加盟商记录")
        
        # 检查状态变化
        changes, updated_status = check_status_changes(last_status, current_records)
        
        # 执行同步操作
        if changes["terminated"] or changes["renewed"]:
            logging.info(f"发现 {len(changes['terminated'])} 个终止加盟商, {len(changes['renewed'])} 个再次签约加盟商")
            simulate_sync_operations(changes)
        else:
            logging.info("未发现状态变化")
        
        # 保存更新后的状态
        try:
            with open(status_file, 'w', encoding='utf-8') as f:
                json.dump(updated_status, f, ensure_ascii=False, indent=2)
            logging.info(f"保存了 {len(updated_status)} 个加盟商的当前状态")
        except Exception as e:
            logging.error(f"保存状态文件失败: {e}")
        
        log_end()
        
        return 0
        
    except Exception as e:
        logging.error(f"任务执行失败: {e}", exc_info=True)
        return 1

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)