import json
from pathlib import Path
import sys


def loadNixpkgs(source: Path, nixpkgs: str) -> dict:
    if not source.exists():
        print(f"{source} does not exist.")
        sys.exit(1)

    with source.open(mode="r") as f:
        src = json.load(f)
        if nixpkgs not in src["nodes"]:
            print(f"There is no {nixpkgs} entry in {source}")
            sys.exit(1)
        return src["nodes"][nixpkgs]


def writeNixpkgs(nixpkgs: dict, target: Path):
    if not target.exists():
        print(f"{target} does not exist.")
        sys.exit(1)

    with target.open(mode="r+") as f:
        tgt = json.load(f)
        if "nixpkgs" not in tgt["nodes"]:
            print(f"There is no nixpkgs entry in {target}")
            sys.exit(1)

        tgt["nodes"]["nixpkgs"] = nixpkgs

        f.seek(0)
        json.dump(tgt, f, indent=2)
        f.truncate()
