import frappe


def execute():
    """Backfill a stable custom_si_row_key for existing Sales Invoice Item rows.

    Phase 1 of the multi tax-article migration. Only fills missing row keys so
    that future joins from `Sales Invoice Item` to `Sales Invoice Tax Article`
    are reliable. Does NOT touch tax_article values (history keeps its single
    value, which the taxes_az consumers still read during the transition).
    """
    if not frappe.db.has_column("Sales Invoice Item", "custom_si_row_key"):
        return

    rows = frappe.db.get_all(
        "Sales Invoice Item",
        filters={"custom_si_row_key": ["in", ["", None]]},
        pluck="name",
    )
    for name in rows:
        frappe.db.set_value(
            "Sales Invoice Item",
            name,
            "custom_si_row_key",
            "r" + frappe.generate_hash(length=10),
            update_modified=False,
        )

    frappe.db.commit()
    frappe.logger().info(f"backfill_si_tax_article_row_keys: filled {len(rows)} row keys")
