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

# 提取服务信息的函数
def extract_service_info(file_path):
    """从文件中提取服务信息，返回服务名称和镜像的字典"""
    services = {}
    
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        
        # 跳过表头
        for line in lines[2:]:
            if line.strip():
                # 使用固定宽度解析每行数据
                try:
                    # 从固定位置提取各字段
                    name_part = line[12:42].strip()  # 服务名称
                    image_part = line[70:136].strip()  # 镜像名称
                    
                    # 只有当name和image都有值时才添加
                    if name_part and image_part:
                        # 保存原始名称和镜像
                        services[name_part] = image_part
                except Exception as e:
                    print(f"解析行时出错: {line.strip()}, 错误: {e}")
    
    return services

def normalize_service_name(service_name):
    """标准化服务名称，移除环境前缀，处理大小写和分隔符差异"""
    # 转换为小写以处理大小写差异
    normalized = service_name.lower()
    
    # Blue环境的服务名称处理
    blue_patterns = [
        'blue-php_', 'blue-ppos_', 'blue_api_', 'blue_web_'
    ]
    for pattern in blue_patterns:
        if normalized.startswith(pattern.lower()):
            normalized = normalized[len(pattern):]
            break
    
    # Green环境的服务名称处理
    green_patterns = [
        'papacore_', 'pposmix_', 'cron_', 'dataserv_', 'imgser_', 'ppcscore_'
    ]
    for pattern in green_patterns:
        if normalized.startswith(pattern.lower()):
            normalized = normalized[len(pattern):]
            break
    
    # 替换所有分隔符为下划线，统一格式
    normalized = re.sub(r'[-_]+', '_', normalized)
    
    # 移除可能的前后空格
    normalized = normalized.strip('_')
    
    return normalized

def compare_services(blue_services, green_services):
    """比较两个环境中的服务镜像"""
    # 1. blue_services 已经是 name 为 key，image 为值的字典对象
    # 2. green_services 已经是 name 为 key，image 为值的字典对象
    
    # 创建标准化名称到原始名称和镜像的映射
    blue_norm_map = {normalize_service_name(name): (name, image) for name, image in blue_services.items()}
    green_norm_map = {normalize_service_name(name): (name, image) for name, image in green_services.items()}


    # print(blue_norm_map)
    print("=" * 80)
    print(green_norm_map)
    
    # 显示所有Blue和Green环境的服务镜像对比
    print("=== Blue环境与Green环境服务镜像详细对比 ===")
    print("{:<35} {:<65} {:<65}".format("服务名称", "Blue镜像", "Green镜像"))
    print("=" * 80)
    
    # 统计变量
    different_count = 0
    same_count = 0
    
    # 创建数组用于存储更新命令
    update_commands = []
    
    # 遍历Blue环境中的每个服务（使用标准化名称进行比较）
    for norm_name, (blue_name, blue_image) in blue_norm_map.items():
        # 初始化green_name和green_image为默认值
        green_name = "-"  # 表示未找到对应服务
        green_image = "-"
        
        # if norm_name == "member_middleplatform":
        #     green_name, green_image = green_norm_map.get("ppos_member_middlepla", ("未找到", ""))
        
        # if norm_name == "device_api":
        #     green_name, green_image = green_norm_map.get("ppos_device_api", ("未找到", ""))
        
        # if norm_name == "events-api":
        #     green_name, green_image = green_norm_map.get("ppos_events_api", ("未找到", ""))
        
        # if norm_name == "ac-api":
        #     green_name, green_image = green_norm_map.get("ppos_ac_api", ("未找到", ""))


        if norm_name in green_norm_map:
            green_name, green_image = green_norm_map[norm_name]
       
        print(norm_name, blue_name, green_name)
        
        # 查找Green环境中是否有相同标准化名称的服务
        #if norm_name in green_norm_map:
            # 打印Blue中与Green不同的服务
            # if blue_image != green_image:
            #     print("{:<35} {:<65} {:<65}".format(
            #         blue_name[:30] + "..." if len(blue_name) > 30 else blue_name,
            #         blue_image[:60] + "..." if len(blue_image) > 60 else blue_image,
            #         green_image[:60] + "..." if len(green_image) > 60 else green_image
            #     ))
            #     # 生成更新命令并添加到数组中
            #     update_command = generate_update_command(blue_name, green_image)
            #     update_commands.append(update_command)
            #     different_count += 1
            # else:
            #     same_count += 1
    
    # # 显示Green环境中特有但Blue环境没有的服务
    # print()
    # print("=== Green环境中特有但Blue环境没有的服务 ===")
    # for norm_name, (green_name, green_image) in green_norm_map.items():
    #     if norm_name not in blue_norm_map:
    #         print("{:<35} {:<65}".format(
    #             green_name[:30] + "..." if len(green_name) > 30 else green_name,
    #             green_image[:60] + "..." if len(green_image) > 60 else green_image
    #         ))
    
    # # 打印所有更新命令
    # if update_commands:
    #     print()
    #     print("=== 推荐的更新命令 ===")
    #     for command in update_commands:
    #         print(command)
    
    # print()
    # print(f"Blue和Green环境中名称相同但镜像不同的服务总数: {different_count}")
    # print(f"Blue和Green环境中名称相同且镜像相同的服务总数: {same_count}")

# 添加一个函数 生成`docker service update --force --image hub.wesais.cn/ppos-pro/pposorder:v.250910.1819 blue-ppos_PPOSOrder`
def generate_update_command(service_name, image):
    """生成更新服务镜像的命令"""
    return f"docker service update --force --image {image} {service_name}"



def main():
    """主函数，比较两个环境中的服务镜像"""
    blue_path = '/home/geng/mydate/deploy.stack/g-b/blue'
    green_path = '/home/geng/mydate/deploy.stack/g-b/green'
    
    # 提取服务信息
    blue_services = extract_service_info(blue_path)
    green_services = extract_service_info(green_path)
    # print(blue_services)
    # print(green_services)
    
    # 比较服务镜像
    compare_services(blue_services, green_services)

if __name__ == "__main__":
    main()