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

import csv
import re
import subprocess
from pathlib import Path


def main():
    csv_path = Path("/hdd1b/cryosparc/nbdbStatic/script/imagedb_entry.csv")
    base_dir = Path("/hdd1b/cryosparc/nbdbStatic/EMPIAR")
    max_rows = 3100  # 实际只处理前x条（从第2行开始）

    with csv_path.open("r", encoding="utf-8", newline="") as f:
        reader = csv.reader(f)

        next(reader, None)  # 跳过表头（第1行）
        processed = 0

        for row in reader:
            if not row:
                continue
            if processed >= max_rows:
                break

            first_col = str(row[0]).strip()
            m = re.search(r"\b(\d{5})\b", first_col)
            if not m:
                print(f"跳过（未匹配5位数字）：{first_col}")
                processed += 1
                continue

            xxxxx = m.group(1)
            target_dir = base_dir / xxxxx
            gif_file = target_dir / f"{xxxxx}-l.gif"
            url = f"https://www.ebi.ac.uk/pdbe/emdb-empiar/entryIcons/{xxxxx}-l.gif"

            if gif_file.exists():
                print(f"已存在，跳过下载：{gif_file}")
                processed += 1
                continue

            target_dir.mkdir(parents=True, exist_ok=True)

            cmd = [
                "wget",
                "-P",
                str(target_dir),
                url,
            ]

            print("执行:", " ".join(cmd))
            subprocess.run(cmd, check=True)

            processed += 1


if __name__ == "__main__":
    main()