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("【更激进的识别方式：列出所有与6月相同的7月/8月仕訳】")
print("=" * 160)

# 找出6月的所有仕訳模式
cur.execute("""
    WITH june_entries AS (
        SELECT 
            je.journal_entry_id,
            je.description,
            COALESCE(SUM(jl.debit), 0)::BIGINT as total_debit,
            COALESCE(SUM(jl.credit), 0)::BIGINT as total_credit
        FROM journal_entries je
        LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
        WHERE je.is_deleted = false
          AND je.is_latest = true
          AND EXTRACT(YEAR FROM je.entry_date) = 2025
          AND EXTRACT(MONTH FROM je.entry_date) = 6
        GROUP BY je.journal_entry_id, je.description
    ),
    july_august_entries AS (
        SELECT 
            je.journal_entry_id,
            je.entry_date,
            EXTRACT(MONTH FROM je.entry_date)::INT as month,
            je.description,
            COALESCE(SUM(jl.debit), 0)::BIGINT as total_debit,
            COALESCE(SUM(jl.credit), 0)::BIGINT as total_credit
        FROM journal_entries je
        LEFT JOIN journal_lines jl ON je.journal_entry_id = jl.journal_entry_id
        WHERE je.is_deleted = false
          AND je.is_latest = true
          AND EXTRACT(YEAR FROM je.entry_date) = 2025
          AND EXTRACT(MONTH FROM je.entry_date) IN (7, 8)
        GROUP BY je.journal_entry_id, je.entry_date, je.description
    )
    SELECT 
        ja.journal_entry_id,
        ja.entry_date,
        ja.month,
        ja.description,
        ja.total_debit,
        ja.total_credit
    FROM july_august_entries ja
    INNER JOIN june_entries je ON ja.description = je.description
        AND ja.total_debit = je.total_debit
        AND ja.total_credit = je.total_credit
    ORDER BY ja.entry_date, ja.journal_entry_id
""")

candidates = cur.fetchall()

print(f"\n找到 {len(candidates)} 条【与6月相同的７月/８月仕訳】")
print("\n这些都是与6月有完全相同描述和金额的仕訳，很可能就是复制出来的\n")

duplicates_for_deletion = []

for entry_id, entry_date, month, description, debit, credit in candidates:
    print(f"ID={entry_id:3d} | {entry_date} | MT={month} | 借={debit:>12,}  貸={credit:>12,} | {description[:60]}")
    
    duplicates_for_deletion.append({
        'entry_id': entry_id,
        'date': entry_date,
        'month': month,
        'description': description,
        'debit': debit,
        'credit': credit
    })

print("\n" + "=" * 160)
print("【删除影响分析】")
print("=" * 160)

# 计算当前余额
cur.execute("""
    SELECT 
        COALESCE(SUM(COALESCE(jl.debit, 0) - COALESCE(jl.credit, 0)), 0) as balance
    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"\n现在普通預金期末残高: {current_balance:>15,.0f}円")

# 详细列出每个要删除的记录对普通預金的影响
print("\n删除后普通預金的变化：\n")

total_impact = 0
for dup in duplicates_for_deletion:
    cur.execute("""
        SELECT COALESCE(SUM(COALESCE(jl.debit, 0) - COALESCE(jl.credit, 0)), 0)
        FROM journal_lines jl
        WHERE jl.journal_entry_id = %s
        AND jl.account_id = 2
    """, (dup['entry_id'],))
    
    impact = cur.fetchone()[0]
    total_impact += impact
    
    if impact != 0:
        print(f"  ID={dup['entry_id']:3d}: {impact:>15,.0f}円 ({dup['date']} {dup['description'][:40]})")

expected_after = current_balance - total_impact

print(f"\n普通預金的总变化: -{total_impact:>15,.0f}円")
print(f"\n删除前普通預金期末残高:      {current_balance:>15,.0f}円")
print(f"删除后普通預金期末残高:      {expected_after:>15,.0f}円")

print(f"\n期望目标值: 14,916,322円")

if expected_after == 14_916_322:
    print(f"✓ 完美匹配！")
elif expected_after > 14_916_322:
    print(f"∆ 删除后高于目标: {expected_after - 14_916_322:>15,.0f}円")
else:
    print(f"∆ 删除后低于目标: {14_916_322 - expected_after:>15,.0f}円")

print("\n" + "=" * 160)
print(f"建议删除的IDs [{len(duplicates_for_deletion)}件]:")
delete_ids = [dup['entry_id'] for dup in duplicates_for_deletion]
print(delete_ids)
print("=" * 160)

cur.close()
conn.close()
