import uuid

src = input if isinstance(input, dict) else {}
rows = input.get("rows") or []
action = str(src.get("action") or "").strip()
fields = ("name", "svg", "settings", "project_id", "updated_at", "luna_history")

def merge_fields(meta):
    for key in fields:
        if key in src:
            meta[key] = src[key]
    return meta

def display_name(meta, fallback):
    name = str(meta.get("name") or fallback or "Untitled logo").strip()
    return name[:200]

if action == "add":
    code = "logo-" + uuid.uuid4().hex[:12]
    meta = merge_fields({})
    output = {"code": code, "label": display_name(meta, code), "meta": meta}
elif action in ("update", "remove"):
    code = str(src.get("code") or "").strip()
    if not code:
        raise ValueError(action + " needs the project row code")
    current = None
    for row in rows:
        if isinstance(row, dict) and row.get("code") == code:
            current = row
            break
    if current is None:
        raise ValueError("no saved logo project " + repr(code))
    meta = dict(current.get("meta") or {})
    if action == "update":
        merge_fields(meta)
    else:
        meta["deleted"] = True
    output = {
        "code": code,
        "label": display_name(meta, current.get("label")),
        "meta": meta
    }
else:
    raise ValueError("logo project commit needs action: add|update|remove")
