import psycopg2

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

cur = conn.cursor()

print("=" * 160)
print("【要确认的关键仕訳】")
print("=" * 160)

# 查询ID 444和445的current状态
for entry_id in [444, 445]:
    print(f"\n--- ID={entry_id} ---")
    
    cur.execute("""
        SELECT 
            je.journal_entry_id,
            je.entry_date,
            je.description,
            je.is_latest,
            je.is_deleted,
            COALESCE(SUM(jl.debit), 0) as debit,
            COALESCE(SUM(jl.credit), 0) as credit
        FROM journal_entries je
        LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
        WHERE je.journal_entry_id = %s
        GROUP BY je.journal_entry_id, je.entry_date, je.description, je.is_latest, je.is_deleted
    """, (entry_id,))
    
    result = cur.fetchone()
    if result:
        je_id, date, desc, is_latest, is_deleted, debit, credit = result
        print(f"日付: {date}")
        print(f"摘要: {desc}")
        print(f"is_latest: {is_latest}, is_deleted: {is_deleted}")
        print(f"仕訳: 借={debit:>12,.0f}  貸={credit:>12,.0f}")
    else:
        print("存在しません")

# 查询所有is_deleted=true但金额较大的仕订
print("\n" + "=" * 160)
print("【削除済みの大きい仕訳（is_deleted=true）】")
print("=" * 160)

cur.execute("""
    WITH deleted_with_impact AS (
        SELECT 
            je.journal_entry_id,
            je.entry_date,
            je.description,
            je.is_latest,
            COALESCE(SUM(jl.debit), 0) as total_debit,
            COALESCE(SUM(jl.credit), 0) as total_credit,
            COALESCE(SUM(CASE WHEN jl.account_id = 2 THEN jl.debit - jl.credit ELSE 0 END), 0) as bank_impact
        FROM journal_entries je
        LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
        WHERE je.is_deleted = true
        AND EXTRACT(YEAR FROM je.entry_date) = 2025
        GROUP BY je.journal_entry_id, je.entry_date, je.description, je.is_latest
    )
    SELECT *
    FROM deleted_with_impact
    WHERE ABS(total_debit - total_credit) > 100000
    ORDER BY ABS(bank_impact) DESC
    LIMIT 20
""")

deleted_entries = cur.fetchall()
print(f"\n金額100万以上が削除（最大20件）：\n")

for je_id, date, desc, is_latest, debit, credit, bank_impact in deleted_entries:
    print(f"ID={je_id:3d} | {date} | 借={debit:>12,.0f}  貸={credit:>12,.0f} | 普通預金への影响={bank_impact:>12,.0f}円")
    print(f"       └─ {desc[:80]}")

print("\n" + "=" * 160)
print("【復旧すべき削除仕訳の推奨】")
print("=" * 160)

# 計算期待値とのギャップ
target_balance = 14_916_322
current_balance = 11_685_193
gap = target_balance - current_balance

print(f"\n期望値: {target_balance:>15,.0f}円")
print(f"現在値: {current_balance:>15,.0f}円")
print(f"ギャップ: {gap:>15,.0f}円")

if gap > 0:
    print(f"\n→ {gap:,}円分の入金（または出金削減）が必要")
    
    # 找出删除的仕訳中，哪些恢复后能接近目标
    cur.execute("""
        SELECT 
            je.journal_entry_id,
            je.entry_date,
            je.description,
            COALESCE(SUM(CASE WHEN jl.account_id = 2 THEN jl.debit - jl.credit ELSE 0 END), 0) as bank_impact
        FROM journal_entries je
        LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
        WHERE je.is_deleted = true
        AND EXTRACT(YEAR FROM je.entry_date) = 2025
        AND je.is_latest = true
        GROUP BY je.journal_entry_id, je.entry_date, je.description
        ORDER BY bank_impact DESC
    """)
    
    restored_balance = current_balance
    print(f"\n削除済みの仕訳を復旧した場合のシミュレーション：\n")
    
    for je_id, date, desc, impact in cur.fetchall():
        if impact != 0:
            restored_balance += impact
            print(f"ID={je_id:3d}: {date} | impact={impact:>12,.0f} → balance={restored_balance:>12,.0f}")
            
            if abs(restored_balance - target_balance) < abs(current_balance - target_balance):
                print(f"        ✓ これを復旧すると目標値に近くなります")

cur.close()
conn.close()
