"""Check what item_code/item_name values look like in tabSales Invoice Item."""
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()

r = frappe.db.sql('SELECT item_code, COUNT(*) as cnt FROM "tabSales Invoice Item" GROUP BY item_code ORDER BY cnt DESC LIMIT 20')
print("item_code distribution:")
for row in r:
    print(f"  {row[1]:>10}  {repr(row[0])}")

r2 = frappe.db.sql('SELECT item_name, COUNT(*) as cnt FROM "tabSales Invoice Item" GROUP BY item_name ORDER BY cnt DESC LIMIT 15')
print("\nitem_name distribution:")
for row in r2:
    print(f"  {row[1]:>10}  {repr(row[0][:80] if row[0] else None)}")

# Check a sample invoice with items
r3 = frappe.db.sql("""SELECT sii.item_code, sii.item_name, sii.description, sii.income_account
    FROM "tabSales Invoice Item" sii LIMIT 5""")
print("\nSample items:")
for row in r3:
    print(f"  code={repr(row[0][:40] if row[0] else None)}  name={repr(row[1][:40] if row[1] else None)}  acct={row[3]}")

frappe.destroy()
