import os

def generate_files(start_sn, count):
    # 1. 解析起始序列号 (分离前缀和最后4位数字)
    # 假设格式固定，最后4位为数字
    prefix = start_sn[:-4]
    try:
        start_num = int(start_sn[-4:])
    except ValueError:
        print("错误: 序列号最后4位必须是数字。")
        return

    csv_filename = "yz_project.csv"
    docker_filename = "docker-compose.yml"
    
    csv_content = []
    docker_services = []

    # docker-compose 头部定义（移除了公共 volumes，改在下方服务中动态生成）
    docker_header = """version: '3'
x-service-common: &service-common
  image: swr.cn-north-4.myhuaweicloud.com/cloud-yuzhen/yuzhen_base:v1.0.12
  restart: always

services:"""

    print(f"正在生成 {count} 个序列号，起始于: {start_sn}...")
    server_ip = "192.168.1.244"  # 替换为实际的服务器 IP
    for i in range(count):
        # 计算当前数字并补零至4位 (例如: 1 -> 0001)
        current_num = start_num + i
        current_sn = f"{prefix}{current_num:04d}"

        # --- 生成 CSV 行 ---
        # 格式: ${device_SN},Horseman-A21,H21.0.0.1,121.36.13.175,1883,mxpoty5rco1jhwde|${device_SN}|2,pykqg5qpzspfce3w,0,121.36.13.175,http://121.36.13.175/dlp/v1/device/backupAndRestore?sn=${device_SN},,

        csv_line = (
            f"{current_sn},Horseman-A21,H21.0.0.1,{server_ip},1883,mxpoty5rco1jhwde|{current_sn}|2,pykqg5qpzspfce3w,0,{server_ip},http://{server_ip}/dlp/v1/device/backupAndRestore?sn={current_sn}"
        )
        csv_content.append(csv_line)

        # --- 生成 Docker Compose 服务块 ---
        # 1. 保持原有的 csv 挂载
        # 2. 新增宿主机当前目录下以容器名（序列号）命名的文件夹，映射到容器内 /yuzhen_iot
        service_block = f"""
  {current_sn}:
    <<: *service-common
    command: [ "/home/start.sh", "{current_sn}" ]
    volumes:
      - ./yz_project.csv:/home/yz_project.csv
      - ./{current_sn}:/yuzhen_iot"""
        docker_services.append(service_block)

    # 2. 写入 CSV 文件
    with open(csv_filename, 'w', encoding='utf-8') as f:
        f.write("\n".join(csv_content))
    print(f"已创建: {csv_filename}")

    # 3. 写入 Docker Compose 文件
    with open(docker_filename, 'w', encoding='utf-8') as f:
        f.write(docker_header)
        f.write("".join(docker_services))
    print(f"已创建: {docker_filename}")

if __name__ == "__main__":
    # --- 配置区域 ---
    START_SN = "YZXHRAX86NN2511250001"  # 起始序列号
    COUNT = 166                       # 需要生成的个数
    # ----------------
    
    generate_files(START_SN, COUNT)