import psycopg2

conn = psycopg2.connect(
    host="192.168.0.61",
    port=55432,
    database="njts_acct",
    user="njts_app",
    password="njts_app2025"
)

cur = conn.cursor()

# 获取account 102的ID
cur.execute("SELECT account_id FROM accounts WHERE account_code = '102'")
account_id = cur.fetchone()[0]

# 查询普通預金 2025年8月的数据
cur.execute("""
    SELECT 
        je.journal_entry_id,
        je.entry_date,
        je.description,
        je.revision_count,
        je.is_latest,
        je.is_deleted,
        SUM(CASE WHEN jl.account_id = %s THEN jl.debit ELSE 0 END) as debit,
        SUM(CASE WHEN jl.account_id = %s THEN jl.credit ELSE 0 END) as credit
    FROM journal_entries je
    LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
    WHERE je.entry_date >= '2025-08-01' 
      AND je.entry_date < '2025-09-01'
    GROUP BY je.journal_entry_id, je.entry_date, je.description, je.revision_count, je.is_latest, je.is_deleted
    ORDER BY je.entry_date DESC, je.journal_entry_id DESC
""", (account_id, account_id))

results = cur.fetchall()

print("=" * 120)
print("普通預金 2025年8月 明細分析")
print("=" * 120)

# 分类统计
total_debit = 0
total_credit = 0
not_deleted_debit = 0
not_deleted_credit = 0
not_deleted_latest_debit = 0
not_deleted_latest_credit = 0

if results:
    for entry_id, entry_date, description, rev_count, is_latest, is_deleted, debit, credit in results:
        debit = debit or 0
        credit = credit or 0
        
        if debit > 0 or credit > 0:
            total_debit += debit
            total_credit += credit
            
            deleted_mark = "【削除】" if is_deleted else "      "
            latest_mark = "✓" if is_latest else "✗"
            print(f"{entry_date} {deleted_mark} [{latest_mark}v{rev_count}] ID={entry_id:3d} | 借={debit:>14,.0f}  貸={credit:>14,.0f} | {description[:40]}")
            
            if not is_deleted:
                not_deleted_debit += debit
                not_deleted_credit += credit
                
                if is_latest:
                    not_deleted_latest_debit += debit
                    not_deleted_latest_credit += credit

print("\n" + "=" * 120)
print("統計")
print("=" * 120)
print(f"全体合計（すべて）: 借={total_debit:>15,.0f}  貸={total_credit:>15,.0f}")
print(f"【削除】以外：      借={not_deleted_debit:>15,.0f}  貸={not_deleted_credit:>15,.0f}")
print(f"【削除】以外で最新: 借={not_deleted_latest_debit:>15,.0f}  貸={not_deleted_latest_credit:>15,.0f}")

# 試算表で使う条件：is_deleted=false AND is_latest=true
print(f"\n✓ 試算表に計上されるべき条件 (is_deleted=false AND is_latest=true):")
print(f"  借={not_deleted_latest_debit:>15,.0f}  貸={not_deleted_latest_credit:>15,.0f}")

# チェック：削除されたが最新になっているものを検出
print("\n⚠️ 問題検出: 削除されているのに is_latest=true のもの")
for entry_id, entry_date, description, rev_count, is_latest, is_deleted, debit, credit in results:
    debit = debit or 0
    credit = credit or 0
    if is_deleted and is_latest and (debit > 0 or credit > 0):
        print(f"  ID={entry_id}: {description} | 借={debit:>14,.0f}  貸={credit:>14,.0f}")

cur.close()
conn.close()
