"""
Reference image tracking for metadata.

Records which reference images were actually sent to NanoBanana
during generation, making generations auditable.
"""

from pathlib import Path


# Valid roles for reference images
ROLES = {
    "characteristic_shot",  # Overall visual style reference
    "character_ref",        # Character reference sheet / portrait
    "location_ref",         # Location reference photo
    "object_ref",           # Object reference photo
    "style_board",          # Style board from S3-style
    "title_artwork",        # Title artwork from S3-style
    "dependency_ref",       # Dependency asset sheet (depends_on)
    "base_frame",           # Frame being refined (stage 08)
    "refined_from",         # Previous iteration image (refine mode)
    "person_ref",           # Product-mode person reference
}

# Valid sources
SOURCES = {
    "reference",   # From references/ directory
    "frame",       # From frame_index fallback
    "iteration",   # Pipeline output (previous iteration, characteristic shot)
}


def build_reference_record(reference_images, project_root, ref_roles=None):
    """Convert raw image paths to metadata-ready records.

    Args:
        reference_images: List of absolute image path strings.
        project_root: Project root path (for making paths relative).
        ref_roles: Optional parallel list of dicts with keys:
            - role: str (from ROLES)
            - asset_id: str (e.g., "tom_morrison", "scorpion_desert")
            - source: str (from SOURCES)
            If shorter than reference_images, remaining entries get defaults.

    Returns:
        List of dicts: [{"path": "relative/path.jpg", "role": "character_ref",
                         "asset_id": "tom", "source": "reference"}, ...]
    """
    if not reference_images:
        return []

    project_root = Path(project_root)
    ref_roles = ref_roles or []
    records = []

    for i, img_path in enumerate(reference_images):
        img_path = Path(img_path)

        # Make path relative to project root
        try:
            rel_path = str(img_path.relative_to(project_root))
        except ValueError:
            rel_path = str(img_path)

        # Get role info (or defaults)
        if i < len(ref_roles) and ref_roles[i]:
            info = ref_roles[i]
        else:
            info = {}

        record = {
            "path": rel_path,
            "role": info.get("role", "unknown"),
            "asset_id": info.get("asset_id"),
            "source": info.get("source", "unknown"),
        }

        # Drop None asset_id to keep records clean
        if record["asset_id"] is None:
            del record["asset_id"]

        records.append(record)

    return records
