"""Insert pictures into worksheets from base64-encoded image data."""

import base64
import os
import tempfile


def add_picture(ws, name: str, base64_data: str, anchor_cell: str):
    """Add a picture to the worksheet from base64 data.

    ws: raw COM Worksheet object
    name: unique name for the picture
    base64_data: base64-encoded PNG or JPEG data (no data URI prefix)
    anchor_cell: cell address like "A1" where top-left corner is anchored
    """
    if not base64_data:
        raise ValueError('base64_data must be non-empty')

    image_bytes = base64.b64decode(base64_data)

    # Validate magic bytes
    if image_bytes[:4] == b'\x89PNG':
        ext = '.png'
    elif image_bytes[:2] == b'\xff\xd8':
        ext = '.jpg'
    else:
        raise ValueError('Not a valid PNG or JPEG image')

    # Remove existing shape with the same name
    for i in range(ws.Shapes.Count, 0, -1):
        if ws.Shapes.Item(i).Name == name:
            ws.Shapes.Item(i).Delete()
            break

    tmp_path = None
    try:
        with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as tmp:
            tmp.write(image_bytes)
            tmp_path = tmp.name

        cell = ws.Range(anchor_cell)
        shape = ws.Shapes.AddPicture(
            tmp_path,
            False,  # LinkToFile
            True,  # SaveWithDocument
            cell.Left,
            cell.Top,
            -1,  # Width  — original size
            -1,  # Height — original size
        )
        # If Excel didn't honour -1, reset scale to original dimensions
        shape.ScaleWidth(1, True)
        shape.ScaleHeight(1, True)
        shape.Name = name
        return shape
    finally:
        if tmp_path:
            try:
                os.unlink(tmp_path)
            except OSError:
                pass
