import psycopg2
from psycopg2.extras import RealDictCursor

conn = psycopg2.connect('host=192.168.0.61 port=55432 dbname=njts_acct user=njts_app password=njts_app2025')
cur = conn.cursor(cursor_factory=RealDictCursor)

print("=" * 100)
print("【檢查修正後的交易序列】")
print("=" * 100)

# 查詢最後3個Entry#375, 376, 377
cur.execute('''
SELECT 
  je.journal_entry_id,
  je.entry_date,
  je.description,
  je.parent_entry_id,
  je.is_deleted,
  SUM(CASE WHEN jl.debit::numeric > 0 THEN jl.debit::numeric ELSE 0 END) as debit_total,
  SUM(CASE WHEN jl.credit::numeric > 0 THEN jl.credit::numeric ELSE 0 END) as credit_total
FROM journal_entries je
LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
WHERE je.journal_entry_id >= 375
  AND je.is_deleted = false
GROUP BY je.journal_entry_id, je.entry_date, je.description, je.parent_entry_id, je.is_deleted
ORDER BY je.journal_entry_id
''')

rows = cur.fetchall()
print("\n【Entry序列】")
for row in rows:
    parent_str = f"parent={row['parent_entry_id']}" if row['parent_entry_id'] else "parent=None"
    desc_short = row['description'][:50] if row['description'] else "N/A"
    print(f"\nEntry#{row['journal_entry_id']}: {parent_str}")
    print(f"  Description: {desc_short}")
    print(f"  Amount: 借 {row['debit_total']:>10,.0f} | 貳 {row['credit_total']:>10,.0f}")
    print(f"  Deleted: {row['is_deleted']}")

print("\n" + "=" * 100)
print("【分析過濾結果】")
print("=" * 100)

# 模擬試算表過濾，逐步檢查
cur.execute('''
SELECT 
  je.journal_entry_id,
  je.parent_entry_id,
  (SELECT COUNT(*) FROM journal_entries child WHERE child.parent_entry_id = je.journal_entry_id AND child.is_deleted = false) as child_count,
  SUM(CASE WHEN jl.debit::numeric > 0 THEN jl.debit::numeric ELSE 0 END) as debit_total,
  SUM(CASE WHEN jl.credit::numeric > 0 THEN jl.credit::numeric ELSE 0 END) as credit_total
FROM journal_entries je
LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
WHERE je.journal_entry_id >= 375
  AND EXTRACT(YEAR FROM je.entry_date) = 2025
  AND EXTRACT(MONTH FROM je.entry_date) = 6
  AND je.is_deleted = false
  AND jl.account_id = 41  -- 売上高
GROUP BY je.journal_entry_id, je.parent_entry_id
ORDER BY je.journal_entry_id
''')

rows = cur.fetchall()
print("\n【完整Entry清單（含child count）】")
total_display = 0
for row in rows:
    parent_str = f"parent={row['parent_entry_id']}" if row['parent_entry_id'] else "parent=None"
    print(f"Entry#{row['journal_entry_id']}: {parent_str} | child: {row['child_count']} | 借 {row['debit_total']:>6,.0f} | 貳 {row['credit_total']:>6,.0f}", end="")
    if row['child_count'] > 0:
        print(" → 被過濾（有child）❌")
    else:
        print(" → 顯示在試算表 ✓")
        total_display += row['debit_total'] if row['debit_total'] else 0
        total_display += row['credit_total'] if row['credit_total'] else 0

print(f"\n試算表顯示金額合計: {total_display:,.0f}")

# 執行實際試算表查詢
cur.execute('''
SELECT 
  SUM(CASE WHEN jl.debit::numeric > 0 THEN jl.debit::numeric ELSE 0 END) as debit_total,
  SUM(CASE WHEN jl.credit::numeric > 0 THEN jl.credit::numeric ELSE 0 END) as credit_total
FROM journal_lines jl
JOIN journal_entries je ON jl.journal_entry_id = je.journal_entry_id
LEFT JOIN journal_entries child ON child.parent_entry_id = je.journal_entry_id
WHERE jl.account_id = 41
  AND EXTRACT(YEAR FROM je.entry_date) = 2025
  AND EXTRACT(MONTH FROM je.entry_date) = 6
  AND je.is_deleted = false
  AND child.journal_entry_id IS NULL
''')

result = cur.fetchone()
actual_debit = result['debit_total'] if result['debit_total'] else 0
actual_credit = result['credit_total'] if result['credit_total'] else 0
print(f"\n【實際試算表結果】")
print(f"借: {actual_debit:,.0f} | 貳: {actual_credit:,.0f}")

conn.close()
