import frappe


def execute():
    """Migrate historic single `tax_article` values into the multi child table.

    Phase 2 of the multi tax-article migration. The Sales-Invoice tax_article
    consumers (VAT Allocation, tax-authority reports) now JOIN
    `Sales Invoice Tax Article` (parent table `custom_item_tax_articles`, linked by
    `custom_si_row_key`). Historic Sales Invoice Items still carry their old single
    `tax_article`; copy each into a child row so reports over past data keep working.
    Idempotent: skips rows already present.
    """
    if not frappe.db.has_column("Sales Invoice Item", "custom_si_row_key"):
        return
    if not frappe.db.exists("DocType", "Sales Invoice Tax Article"):
        return

    items = frappe.db.sql(
        """
        select sii.parent as si, sii.custom_si_row_key as rk, sii.tax_article as ta
        from `tabSales Invoice Item` sii
        where ifnull(sii.tax_article, '') != ''
          and ifnull(sii.custom_si_row_key, '') != ''
        """,
        as_dict=True,
    )

    created = 0
    for it in items:
        already = frappe.db.exists(
            "Sales Invoice Tax Article",
            {
                "parenttype": "Sales Invoice",
                "parent": it.si,
                "parentfield": "custom_item_tax_articles",
                "parent_row": it.rk,
                "tax_article": it.ta,
            },
        )
        if already:
            continue

        max_idx = frappe.db.sql(
            """
            select ifnull(max(idx), 0) from `tabSales Invoice Tax Article`
            where parent=%s and parenttype='Sales Invoice'
              and parentfield='custom_item_tax_articles'
            """,
            it.si,
        )[0][0]

        child = frappe.new_doc("Sales Invoice Tax Article")
        child.parent = it.si
        child.parenttype = "Sales Invoice"
        child.parentfield = "custom_item_tax_articles"
        child.parent_row = it.rk
        child.tax_article = it.ta
        child.idx = (max_idx or 0) + 1
        child.insert(ignore_permissions=True)
        created += 1

    frappe.db.commit()
    frappe.logger().info(
        f"backfill_sales_invoice_tax_articles_history: created {created} child rows"
    )
