"""
GLAMWalk -- Volume 3: Data at Scale
04_nga_objects_images_join.py

Rebuilding NGA data correctly from the real official objects.csv + published_images.csv pair, joined on object ID.

Source: Volume Three, Section 2.2 -- Rebuilding From the Real Source Files
Targets Python 3.11.4 -- see Volume One, Chapter 1.5/1.6.
"""

import csv

def load_nga_objects(objects_csv_path):
    objects = {}
    with open(objects_csv_path, newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            objects[row["objectid"]] = {
                "title": row.get("title"),
                "attribution": row.get("attribution"),   # the column that had gone missing before
                "displaydate": row.get("displaydate"),
                "classification": row.get("classification"),
            }
    return objects

def join_nga_images(objects, images_csv_path):
    complete_records = []
    with open(images_csv_path, newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            obj = objects.get(row["depictstmsobjectid"])
            if not obj:
                continue   # an image record with no matching object — skip, don't guess
            record = dict(obj)
            record["image_url"] = row.get("iiifurl")
            complete_records.append(record)
    return complete_records
