"""A first BAFU inventory with pyvolca 0.11.0 and VoLCA v0.12.0.

Run from a directory where you want a new volca-first-result folder.
No account, LCIA method download, or hosted API access is needed.
"""
from hashlib import sha256
from pathlib import Path
from urllib.request import urlretrieve

URL = "https://app.volca.run/preloaded/bafu-2026-v1.zip"
SHA256 = "5b5742de3bfe31a4cbeca6fe07e29c814e84c3fa5fec4d29fbb771042812664c"
CONFIG = '''[server]
host = "127.0.0.1"
port = 0

[[databases]]
name = "bafu-2026-v1"
path = "bafu-2026-v1.zip"
load = true
'''


def prepare(folder):
    folder.mkdir(exist_ok=True)
    config = folder / "volca.toml"
    if config.exists() and config.read_text() != CONFIG:
        raise RuntimeError(f"Refusing to overwrite {config}. Use a fresh directory.")
    archive = folder / "bafu-2026-v1.zip"
    if not archive.exists():
        urlretrieve(URL, archive)
    with archive.open("rb") as source:
        digest = sha256()
        for chunk in iter(lambda: source.read(1024 * 1024), b""):
            digest.update(chunk)
    if digest.hexdigest() != SHA256:
        raise RuntimeError(f"Checksum mismatch: {archive}. Remove this archive and retry.")
    if not config.exists():
        with config.open("x") as target:
            target.write(CONFIG)
    return config


def main():
    from volca import Client, Server, download

    config = prepare(Path("volca-first-result").resolve())
    installed = download(version="v0.12.0")
    with Server(config=str(config), binary=str(installed.binary)) as server:
        client = Client(base_url=server.base_url, db="bafu-2026-v1", password=server.password)
        matches = client.search_activities(name="Electricity mix", geo="CH", exact=True)
        if len(matches) != 1:
            raise RuntimeError(f"Expected one Swiss electricity mix, got {len(matches)}")
        activity = matches[0]
        print(activity.process_id)
        print(activity.activity_name, activity.location)
        print("Reference:", activity.product_amount, activity.product_unit)
        inventory = client.get_inventory(activity.process_id)
        print("Inventory rows:", len(inventory.flows))
        for flow in inventory.flows[:5]:
            print(flow.quantity, flow.unit_name, flow.flow_name)


if __name__ == "__main__":
    main()
