"""Check invoice naming and legacy_invoice_id mapping."""
import frappe, 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()

# Check invoice names
r = frappe.db.sql('SELECT name, legacy_invoice_id FROM "tabSales Invoice" WHERE legacy_invoice_id > 0 LIMIT 10')
print("Invoice names with legacy_invoice_id:")
for row in r:
    print(f"  name={row[0]}  legacy_id={row[1]}")

# Check item parent vs invoice name
r2 = frappe.db.sql("""
    SELECT sii.parent, sii.idx, sii.item_name, si.legacy_invoice_id
    FROM "tabSales Invoice Item" sii
    JOIN "tabSales Invoice" si ON si.name = sii.parent
    WHERE si.legacy_invoice_id > 0
    LIMIT 10
""")
print("\nItem parent → legacy_invoice_id:")
for row in r2:
    print(f"  parent={row[0]}  idx={row[1]}  legacy_id={row[3]}  name={row[2][:50]}")

# Count
r3 = frappe.db.sql('SELECT COUNT(*) FROM "tabSales Invoice" WHERE legacy_invoice_id > 0')
print(f"\nInvoices with legacy_invoice_id: {r3[0][0]}")
r4 = frappe.db.sql('SELECT COUNT(*) FROM "tabSales Invoice" WHERE legacy_invoice_id IS NULL OR legacy_invoice_id = 0')
print(f"Invoices without legacy_invoice_id: {r4[0][0]}")

frappe.destroy()
