#!/usr/bin/env python3
import argparse
import shutil
import tempfile
from pathlib import Path

from script_common import resolve_repo_root


def main() -> int:
    parser = argparse.ArgumentParser(description="Export local NuGet cache to zip")
    parser.add_argument("--repo-root", default=None)
    parser.add_argument("--output-zip", default="nuget-cache-export.zip")
    parser.add_argument("--include-dotnet-home", action="store_true")
    args = parser.parse_args()

    repo_root = resolve_repo_root(args.repo_root)
    output_zip = (repo_root / args.output_zip).resolve()

    nuget_dir = repo_root / ".nuget"
    dotnet_home = repo_root / ".dotnet_home"
    if not nuget_dir.exists():
        print(f"NuGet cache not found: {nuget_dir}")
        return 2

    with tempfile.TemporaryDirectory() as td:
        stage = Path(td) / "cache-export"
        stage.mkdir(parents=True, exist_ok=True)
        shutil.copytree(nuget_dir, stage / ".nuget")
        if args.include_dotnet_home and dotnet_home.exists():
            shutil.copytree(dotnet_home, stage / ".dotnet_home")
        manifest = stage / "nuget-cache-manifest.txt"
        manifest.write_text("exported_by=nuget-export-cache.py\n", encoding="utf-8")
        archive_base = str(output_zip.with_suffix(""))
        shutil.make_archive(archive_base, "zip", root_dir=str(stage))

    print(f"Exported cache: {output_zip}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
