import fcntl

import time
from contextlib import contextmanager
from pathlib import Path


@contextmanager
def global_io_lock(lock_path: Path):
    """
    使用 GPFS 上的文件作为全局互斥锁。
    当一个 Job 获得锁时，其他 Job 会进入等待状态 (Blocking),
    直到锁被释放。
    """
    # 确保锁文件的目录存在
    if not lock_path.parent.exists():
        lock_path.parent.mkdir(parents=True, exist_ok=True)

    # 打开锁文件
    f = open(lock_path, 'a+')

    try:
        print(f"[IO Lock] Trying to acquire global lock at {lock_path}...", flush=True)
        start_wait = time.time()

        # LOCK_EX: 排他锁 (Exclusive Lock)
        # 默认是阻塞的，如果锁被占用，程序会停在这里等待
        fcntl.lockf(f, fcntl.LOCK_EX)

        wait_time = time.time() - start_wait
        if wait_time > 1:
            print(f"[IO Lock] Waited {wait_time:.1f}s for other jobs to finish copying.", flush=True)
        print(f"[IO Lock] Lock acquired! Starting data relocation...", flush=True)

        yield  # 这里执行真正的复制逻辑

    finally:
        # 释放锁
        print(f"[IO Lock] Releasing lock...", flush=True)
        fcntl.lockf(f, fcntl.LOCK_UN)
        f.close()
        print(f"[IO Lock] Released lock...", flush=True)
