"""Check GL entry date distribution for income accounts."""
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 EXTRACT(YEAR FROM posting_date)::int as y,
           EXTRACT(MONTH FROM posting_date)::int as m,
           COUNT(*)
    FROM "tabGL Entry"
    WHERE account LIKE %s AND credit > 0
    GROUP BY y, m
    ORDER BY y, m
""", ('4020%',))
print("GL entries for 4020 (Mensualite fibre) by month:")
for row in r:
    print(f"  {int(row[0])}-{int(row[1]):02d}: {row[2]} entries")

# Total GL entry date range
r2 = frappe.db.sql("""
    SELECT MIN(posting_date), MAX(posting_date), COUNT(*)
    FROM "tabGL Entry" WHERE credit > 0 AND account NOT LIKE %s AND account NOT LIKE %s
""", ('Comptes%', '%payer%'))
print(f"\nAll income GL: min={r2[0][0]} max={r2[0][1]} count={r2[0][2]}")

frappe.destroy()
