from pathlib import Path
import argparse, shutil, tarfile

ROOT = Path(__file__).resolve().parent
ARCHIVE = ROOT / "FND009-S5_transfer_fixture.tar"
WS = ROOT / "workspace"

parser = argparse.ArgumentParser(description="Materialize the supplied changed-context transfer fixture.")
parser.add_argument("--reset", action="store_true", help="Delete and recreate only transfer_case/workspace/. This is destructive to local work in that directory.")
args = parser.parse_args()

if not ARCHIVE.is_file():
    raise SystemExit("Transfer fixture asset is missing.")
if WS.exists():
    if not args.reset:
        if not (WS / ".git").is_dir():
            raise SystemExit("workspace/ exists but is not the expected Git fixture; ordinary setup will not replace it.")
        print("TRANSFER_FIXTURE_PRESENT_PRESERVED", WS)
        raise SystemExit(0)
    shutil.rmtree(WS)
WS.mkdir(parents=True)
base = WS.resolve()
with tarfile.open(ARCHIVE, "r") as tf:
    members = tf.getmembers()
    for m in members:
        target = (WS / m.name).resolve()
        if target != base and base not in target.parents:
            raise SystemExit("Unsafe path in transfer fixture archive.")
        if m.issym() or m.islnk():
            raise SystemExit("Links are not permitted in the transfer fixture archive.")
    tf.extractall(WS)
if not (WS / ".git").is_dir():
    raise SystemExit("Materialized transfer fixture is not a Git repository.")
print("TRANSFER_FIXTURE_READY", WS)
