import json
import subprocess
import sys
from pathlib import Path

if len(sys.argv) != 3:
    raise SystemExit('Usage: python3 album_inventory.py ALBUM_ID OUTPUT.json')
items = []
for offset in range(0, 100000, 100):
    result = subprocess.run(
        ['5am', 'media', 'list', '--album', sys.argv[1],
         '--limit', '100', '--offset', str(offset)],
        check=True, capture_output=True, text=True,
    )
    page = json.loads(result.stdout)
    if not isinstance(page, list):
        raise SystemExit('Unexpected media list response; check your CLI version')
    items.extend(page)
    if len(page) < 100:
        break
else:
    raise SystemExit('Inventory exceeded the 100,000-item safety cap')
# Exclusive creation protects an existing report from accidental overwrite.
with Path(sys.argv[2]).open('x') as output:
    json.dump(items, output, indent=2)
    output.write('\n')
print(f'Saved {len(items)} returned items to {sys.argv[2]}')
