"""Debug idx matching between legacy and ERPNext."""
import frappe, pymysql, os, sys
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1)
os.chdir("/home/frappe/frappe-bench/sites")
frappe.init(site="erp.gigafibre.ca", sites_path=".")
frappe.connect()

# Get an invoice that still has default income
r = frappe.db.sql("""
    SELECT si.name, si.legacy_invoice_id
    FROM "tabSales Invoice" si
    JOIN "tabSales Invoice Item" sii ON sii.parent = si.name
    WHERE sii.income_account = %s AND si.legacy_invoice_id > 0
    LIMIT 1
""", ("Autres produits d'exploitation - T",))

if not r:
    print("No invoices found with default account!")
    frappe.destroy()
    exit()

inv_name, legacy_id = r[0]
print(f"Invoice: {inv_name}, legacy_id: {legacy_id}")

# ERPNext items
items = frappe.db.sql("""
    SELECT idx, item_name, income_account FROM "tabSales Invoice Item"
    WHERE parent = %s ORDER BY idx
""", (inv_name,))
print(f"\nERPNext items (idx):")
for row in items:
    print(f"  idx={row[0]}  {row[2]}  {row[1][:60]}")

# Legacy items
legacy = pymysql.connect(
    host="legacy-db", user="facturation", password="***LEGACY-DB-PW-REDACTED***",
    database="gestionclient", cursorclass=pymysql.cursors.DictCursor
)
with legacy.cursor() as cur:
    cur.execute("""
        SELECT id, sku, product_name,
               ROW_NUMBER() OVER (PARTITION BY invoice_id ORDER BY id) as rn
        FROM invoice_item WHERE invoice_id = %s ORDER BY id
    """, (int(legacy_id),))
    litems = cur.fetchall()
legacy.close()

print(f"\nLegacy items (ROW_NUMBER):")
for li in litems:
    print(f"  rn={li['rn']}  sku={li['sku']}  {li['product_name'][:60]}")

frappe.destroy()
