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("【期首余额检查】2025年6月1日の期首余额记录")
print("=" * 160)

# 查询是所有关于"期首"或"opening"的仕訳
cur.execute("""
    SELECT 
        je.journal_entry_id,
        je.entry_date,
        je.description,
        je.is_latest,
        je.is_deleted,
        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 EXTRACT(YEAR FROM je.entry_date) = 2025
    AND EXTRACT(MONTH FROM je.entry_date) = 6
    AND (je.description LIKE '%期首%' 
         OR je.description LIKE '%opening%'
         OR je.description LIKE '%前期%'
         OR je.description LIKE '%繰越%')
    GROUP BY je.journal_entry_id, je.entry_date, je.description, je.is_latest, je.is_deleted
    ORDER BY je.entry_date, je.journal_entry_id
""")

results = cur.fetchall()

if results:
    print(f"\n見つかった期首関連仕訳：\n")
    for je_id, date, desc, is_latest, is_deleted, debit, credit, bank_impact in results:
        status = f"latest={is_latest}, deleted={is_deleted}"
        print(f"ID={je_id:3d} | {date} | {status:20} | 借={debit:>12,.0f}  貸={credit:>12,.0f}")
        print(f"       └─ {desc}")
        print(f"       └─ 普通預金への影响: {bank_impact:>12,.0f}円\n")
else:
    print("\n⚠️  期首関連の仕訳が見つかりません！")

# 查询2025年6月の一番早い日付の仕訳
print("\n" + "=" * 160)
print("【確認】2025年6月の仕訳日付範囲")
print("=" * 160)

cur.execute("""
    SELECT 
        MIN(je.entry_date) as earliest_date,
        MAX(je.entry_date) as latest_date,
        COUNT(*) as total_count
    FROM journal_entries je
    WHERE EXTRACT(YEAR FROM je.entry_date) = 2025
    AND EXTRACT(MONTH FROM je.entry_date) = 6
    AND je.is_deleted = false
    AND je.is_latest = true
""")

earliest, latest, cnt = cur.fetchone()
print(f"\n有効な仕訳（is_deleted=false, is_latest=true）:")
print(f"  最早日付: {earliest}")
print(f"  最新日付: {latest}")
print(f"  仕訳件数: {cnt}")

# 如果6月1日没有数据，那就是缺少期首
if earliest and earliest > "2025-06-01":
    print(f"\n⚠️  2025-06-01の仕訳がありません（最早は{earliest}）")
    print("→ 期首余额が入力されていない可能性があります")

# 確認普通预金の期首と期末
print("\n" + "=" * 160)
print("【期首・期末分析】普通預金")
print("=" * 160)

# 取得6月1日和以前的普通預金余额（期首）
cur.execute("""
    SELECT 
        COALESCE(SUM(COALESCE(jl.debit, 0) - COALESCE(jl.credit, 0)), 0)
    FROM journal_lines jl
    INNER JOIN journal_entries je ON jl.journal_entry_id = je.journal_entry_id
    WHERE jl.account_id = 2
    AND je.entry_date < '2025-06-01'
    AND je.is_deleted = false
    AND je.is_latest = true
""")

pre_balance = cur.fetchone()[0]
print(f"\n2025-06-01前の普通預金残高: {pre_balance:>15,.0f}円")

# 取得6月1日的普通預金余额
cur.execute("""
    SELECT 
        COALESCE(SUM(COALESCE(jl.debit, 0) - COALESCE(jl.credit, 0)), 0)
    FROM journal_lines jl
    INNER JOIN journal_entries je ON jl.journal_entry_id = je.journal_entry_id
    WHERE jl.account_id = 2
    AND DATE(je.entry_date) = '2025-06-01'
    AND je.is_deleted = false
    AND je.is_latest = true
""")

june1_balance = cur.fetchone()[0]
print(f"2025-06-01の普通預金残高: {june1_balance:>15,.0f}円")

# 现在的期末余额
cur.execute("""
    SELECT 
        COALESCE(SUM(COALESCE(jl.debit, 0) - COALESCE(jl.credit, 0)), 0)
    FROM journal_lines jl
    INNER JOIN journal_entries je ON jl.journal_entry_id = je.journal_entry_id
    WHERE jl.account_id = 2
    AND je.is_deleted = false
    AND je.is_latest = true
""")

current_balance = cur.fetchone()[0]
print(f"現在の普通預金期末残高: {current_balance:>15,.0f}円")

print(f"\n期首（期待）: 3,231,129円")
print(f"期首（実績）: {pre_balance:>15,.0f}円")
print(f"差額: {3_231_129 - pre_balance:>15,.0f}円")

if pre_balance == 0 and current_balance > 0:
    print("\n⚠️  問題が判明しました！")
    print("  期首残高がデータベースに入力されていません")
    print("  2025-06-01に開始余額仕訳を追加する必要があります")

cur.close()
conn.close()
